Predict the Output: What a Spread Copies
What do the two console.log calls print? Explain why.
let first = { name: "Ada", address: { city: "Leeds", country: "UK" } };
let second = { ...first };
first.name = "Grace";
first.address.city = "York";
console.log(first);
console.log(second);Hints
Hint 1
A spread copies the top-level properties. A nested object is copied as a reference, not as a new object.
Solution
Show the approach
Answer: first is Grace in York; second is still Ada, but also in York
Spread copies top-level properties by value. address is a reference, so both objects share one address object. structuredClone(first), or a cloneDeep, breaks the link.
Assistant
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.
Asked at
Similar Problems6
- Predict the Output: var and let in a Loop With Timerseasy
- Predict the Output: `this` in an Arrow Methodeasy
- Predict the Output: Promise and Timer Ordermedium
- Predict the Output: A then and finally Chainmedium
- Predict the Output: var Hoisting With Shadowingeasy
- Predict the Output: The Temporal Dead Zoneeasy