Shallow cloning

suggest change

Object spread is the concise modern way to copy an object's own enumerable properties into a new object:

const existing = { a: 1, b: 2, c: 3 };
const clone = { ...existing };

Enumerable symbol properties are included as well as string-keyed properties. Nested objects are still shared because this is a shallow copy.

Object.assign() is useful when copying into an existing target:

const target = { a: 0 };
Object.assign(target, existing);

Neither form copies a source object's prototype or property descriptors, and both invoke getters while copying. Use structuredClone() where it is available when nested values must be copied rather than shared.

const source = { nested: { count: 1 } };
const shallowCopy = { ...source };
shallowCopy.nested.count = 2;
console.log(source.nested.count); // 2

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents