Copying Objects

Shallow Copies

Example

The spread operator and Object.assign copy only the top level; nested objects are still shared:

const original = { name: "Asha", address: { city: "Hyderabad" } };
const copy = { ...original };
copy.name = "Copy";
copy.address.city = "Pune";       // changes the shared nested object
console.log(original.name, original.address.city);

Output

Asha Pune

Deep Copies

Example

structuredClone makes a full, independent copy:

const original = { name: "Asha", address: { city: "Hyderabad" }, tags: ["a"] };
const deep = structuredClone(original);
deep.address.city = "Pune";
deep.tags.push("b");
console.log(original.address.city, original.tags);

Output

Hyderabad [ 'a' ]

Note: JSON.parse(JSON.stringify(obj)) also deep-copies, but loses functions, undefined, dates (become strings) and Maps/Sets.

Comparing Objects

Example

Objects are compared by reference, not content:

console.log({ a: 1 } === { a: 1 });
const x = { a: 1 };
const y = x;
console.log(x === y);

Output

false
true