Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Does the spread operator make a deep copy?

Do you know what will be the output of this code?

JavaScript
const a = { n: 1, inner: { m: 1 } };
const b = { ...a };

b.n = 2;
b.inner.m = 2;
console.log(a.n, a.inner.m);
Show answer and explanation

The answer is 1 2.

Spread copies top-level properties. n is copied by value, but inner is copied by reference, so both objects share it. Use structuredClone(a) for a deep copy.

Take the full quiz Next question →

More Objects questions

  1. Why do object keys 1 and "1" overwrite each other?
  2. What happens when you use an object as an object key?
  3. Why is {} === {} false in JavaScript?
  4. Are JavaScript objects copied by reference?
  5. Is Object.freeze deep or shallow?

Related topics