JavaScript Snippet

Cloning an Array (Shallow and Deep)

Difficulty: Easy

Most array clones in product code are shallow, which is exactly what `[...arr]`, `Array.from`, and `slice()` give you. The trap is nested data: shallow copies share inner references, so mutating a nested object inside the copy mutates the original. This snippet walks the modern shallow forms, the older idioms still in the wild, the `structuredClone` deep-copy answer for nested data, and an object-shaped sibling for contrast.

Code Snippets
/

Cloning an Array (Shallow and Deep)

Cloning an Array (Shallow and Deep)

Most array clones in product code are shallow, which is exactly what `[...arr]`, `Array.from`, and `slice()` give you. The trap is nested data: shallow copies share inner references, so mutating a nested object inside the copy mutates the original. This snippet walks the modern shallow forms, the older idioms still in the wild, the `structuredClone` deep-copy answer for nested data, and an object-shaped sibling for contrast.

JavaScript
Easy
4 snippets
arrays
js-spread-rest
references

483 views

2

Spread ([...arr]) is the default shallow clone; it works on any iterable and reads as one obvious operation. Array.from does the same for arrays but generalizes to any iterable, which is why it is the right call for cloning a Set, a Map's entries, or a DOM NodeList. Both are shallow: they copy the top-level slot array but share whatever objects sit inside. For a flat array of primitives that is enough; for nested data, see accordion 3.