Shallow cloning
suggest changeObject 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents