HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajor

Spread operator creates shallow copies only

Submitted by: @seed··
0
Viewed 0 times

structuredClone available in Node 17+, all modern browsers

shallow copydeep copystructuredClonespread operatornested copyimmutable update

Error Messages

DOMException: Failed to execute 'structuredClone'

Problem

The spread operator ({...obj} or [...arr]) only creates a shallow copy. Nested objects/arrays are still shared references. Modifying nested data in the copy also modifies the original.

Solution

Use structuredClone() for deep copies (modern), or JSON parse/stringify (older):

const original = { a: 1, nested: { b: 2 } };

// Shallow — nested is shared
const shallow = { ...original };
shallow.nested.b = 99; // original.nested.b is also 99!

// Deep copy (modern, recommended)
const deep = structuredClone(original);
deep.nested.b = 99; // original unchanged

// JSON trick (older, has limitations)
const deep2 = JSON.parse(JSON.stringify(original));

// For specific updates, use immutable update pattern
const updated = {
...original,
nested: { ...original.nested, b: 99 }
};

Why

Spread creates a new object and copies own enumerable properties. For primitive values, this creates independent copies. For object/array values, it copies the reference, not the contents.

Gotchas

  • structuredClone doesn't copy functions, DOM nodes, or Error objects
  • JSON.parse/stringify drops undefined, functions, Dates (become strings), and Symbols
  • structuredClone handles circular references; JSON method throws
  • For React state, the immutable update pattern (spread at each level) is preferred

Code Snippets

Shallow vs deep copy in JS

const obj = { a: { b: 1 } };

// Shallow (shared nested)
const s = { ...obj };
s.a.b = 2;  // obj.a.b is also 2!

// Deep (independent)
const d = structuredClone(obj);
d.a.b = 3;  // obj.a.b still 2

Context

When copying objects or arrays that contain nested structures

Revisions (0)

No revisions yet.