CodePark/ questions / Equality & copying
START PRACTICINGPRACTICE
Frontend question · JavaScript › Equality & copying

What does this log?

const a = { n: 1, inner: { m: 1 } };
const b = { ...a };
b.n = 2;
b.inner.m = 2;
console.log(a.n, a.inner.m);
1 2

The answer is 1 2. Spread makes a shallow copy. b.n is its own property, so changing it leaves a.n as 1. But b.inner is the same object as a.inner, so the nested change is visible through a.

The tempting option "1 1" is wrong because spread does not copy nested objects. It copies only the reference to them.