JavaScript Shallow, Descriptor and Structured Copies
Quick answer
Copying data, copying descriptors and cloning a supported object graph preserve different aspects of an object. Choose the operation that matches the intended contract.
How it works
Object spread reads enumerable own values into new data properties, and shares nested references. Object.create(Object.getPrototypeOf(o), Object.getOwnPropertyDescriptors(o)) preserves ordinary own descriptors and the prototype link, but shares referenced values. The host structuredClone API clones supported graphs including cycles; it does not preserve arbitrary custom prototypes, accessors or all descriptors and rejects unsupported values such as functions. It is available in the tested Node runtime, not a core ECMAScript built-in.
const a = {}; Object.defineProperty(a,"id",{value:7});const b = {...a}; const c = Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));console.log(b.id,c.id,Object.getOwnPropertyDescriptor(c,"id").writable);Expected output in Node.js:
undefined 7 falseSpread skips the hidden property; descriptor copying preserves it.
const a = {nested:{n:1}}; a.self = a; const b = structuredClone(a);b.nested.n=8; console.log(a.nested.n,b.self===b);Expected output in Node.js:
1 trueThe supported graph is copied, including its cycle and nested data.
Common mistakes
JSON round-tripping is not a universal cloning algorithm; JSON and cloning limits are explored later.
Practice
Compare whether a non-enumerable property and a nested object identity survive each copy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Shallow, Descriptor and Structured Copies — Knowledge Check
Apply the taught concept and predict the output.
Which method returns a mapping of own property descriptors?
Does descriptor copying recursively copy nested objects?
Which value cannot be generally cloned with structuredClone?
What is the exact console output in JavaScript Shallow, Descriptor and Structured Copies example 1?
const a = {}; Object.defineProperty(a,"id",{value:7});const b = {...a}; const c = Object.create(Object.getPrototypeOf(a),Object.getOwnPropertyDescriptors(a));console.log(b.id,c.id,Object.getOwnPropertyDescriptor(c,"id").writable);What is the exact console output in JavaScript Shallow, Descriptor and Structured Copies example 2?
const a = {nested:{n:1}}; a.self = a; const b = structuredClone(a);b.nested.n=8; console.log(a.nested.n,b.self===b);