whatstheoutput_

#51: Spreading an array of arrays

Topic: arrays · Difficulty: ★★

const original = [[1, 2], [3, 4]];
const copy = [...original];
copy[0].push(99);
console.log(original);
console.log(copy === original);

Output

[ [ 1, 2, 99 ], [ 3, 4 ] ]
false

Why

The spread operator [...original] creates a brand-new outer array, which is why copy === original is false. But the copy is only ONE level deep — a shallow copy. Its elements are copied by reference, and since original's elements are themselves arrays (objects), copy and original end up holding references to the very SAME two inner arrays. Pushing 99 onto copy[0] mutates that shared inner array, so the change is visible through original too, even though original itself was never directly touched. Deep structures need a deep clone (e.g. structuredClone) to avoid this aliasing.

More arrays puzzles

Play today's puzzle →