CKTIS / JavaScript
Shallow and deep copying of objects
Assigning an object does not create a copy. A shallow copy creates a new outer object but shares nested objects. A deep copy also recreates nested objects within the supported structure.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
const alias = source;
const shallow = { ...source };
const deepForThisShape = { ...source, nested: { ...source.nested } };The assignment const alias = source copies the reference value, not the object: both variables refer to the same object. A shallow copy created with { ...source } or Object.assign({}, source) has a different identity, but its property values may still refer to the same nested objects. Mutating their contents is therefore visible through both references.
Object spread copies own enumerable properties with string and symbol keys. It does not preserve the source prototype or property descriptors; it reads values, so it can invoke getters. Object.assign also reads values, but writes them using property-setting operations, so it can invoke setters on the target object. These mechanisms are not completely interchangeable.
A deep copy also recreates nested objects within the supported structure instead of sharing them with the source. In the example, deepForThisShape is a deep copy only for the structure shown: the sole nested object contains a number. Another nesting level would require another copying step. Do not treat this pattern as universal cloning: supported types, cycles, and repeated references to the same object must be addressed.
Reference identifiers covered by this entry: shallow and deep copy.
Examples
const source = { name: "Ada", nested: { score: 1 } };
const alias = source;
const shallow = { ...source };
const deepForThisShape = { ...source, nested: { ...source.nested } };
console.log(alias === source);
console.log(shallow === source);
console.log(shallow.nested === source.nested);
console.log(deepForThisShape.nested === source.nested);
shallow.nested.score = 2;
deepForThisShape.nested.score = 3;
console.log(source.nested.score, shallow.nested.score, deepForThisShape.nested.score);Result
true false true false 2 2 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.