Hone

Lessons · JavaScript · ... spread

Copying with three dots

[...a] makes a new array with the same items; {...o} does the same for objects. The copy is one level deep: nested arrays and objects are shared.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Frameworks compare by identity, so 'change the array' means 'make a new one'. Spread is the everyday way to copy, merge and add without touching the original.

How to think about it

Spread to copy or merge the top level. For anything nested that must not be shared, structuredClone. When in doubt, mutate the copy and check the original.

Worked example

const a = [1, [2, 3]];
A nested array.
const b = [...a];
A new outer array.
b.push(4);
Change the copy.
console.log(a.length, b.length);
2 3: the top level is separate.
b[1].push(9);
Change the inner array through the copy.
console.log(a[1]);
[ 2, 3, 9 ]: the inner array is shared, a shallow copy.
console.log({ ...{ x: 1 }, y: 2 });
{ x: 1, y: 2 }: spread works on objects too.

Your turn

A copy of the items.

const copy = [items];

The trap

Spread copies one level. Nested objects and arrays are shared, and structuredClone is the deep copy.

Practise ... spread on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.