Shallow state updates
You need a new top-level object while intentionally sharing nested state.
JS Puzzles · Const
A shallow copy creates a new outer object but keeps references to nested objects. A deep copy recursively duplicates nested properties; structuredClone is the documented built-in for this purpose.
JavaScript object assignment and ordinary copy operations preserve references to nested objects. A shallow copy creates a new outer object but shares nested objects; structuredClone creates a separate copy including nested properties, so later nested mutations do not cross between the values.
structuredClone(value)const original = { user: { name: "Ada" }, tags: ["js"] };
const shallow = { ...original };
const deep = structuredClone(original);
shallow.user.name = "Grace";
deep.tags.push("copy");
console.log(original.user.name); // "Grace": nested object is shared
console.log(original.tags); // ["js"]: deep copy is independentThe spread copy duplicates only the outer object, while structuredClone recursively copies supported nested values.
You need a new top-level object while intentionally sharing nested state.
You need independently mutable nested configuration or application state.
You need to pass cloneable structured data across boundaries without sharing nested references.
Object variables hold references, so assignment copies the reference rather than duplicating the object. A shallow copy creates a new outer object while nested objects remain shared.
Follow-up: What happens if a nested property is mutated through the shallow copy? The original changes too because both copies reference that nested object.
structuredClone recursively clones the object and its nested properties. The resulting object can be changed without changing the original, provided its contents are supported by the structured-cloning algorithm.
Follow-up: Why is JSON serialization not a general replacement? It is limited to JSON-representable data and can lose or transform values outside that format.
Primitive values are copied as values, but object values are references. Therefore, a shallow copy is independent only for properties whose values are primitives.
Follow-up: How can you test whether nested state is shared? Compare the nested references with strict equality, such as copy.child === original.child.
Object.assignstructuredCloneobject referencesprimitivesshallow copydeep cloning