Arrays & objects · Output question
JavaScript shallow copy and a shared nested array
An object spread creates a new outer object. Predict whether a mutation through its nested array changes the original.
const basket = { tags: ["new"] };
const copy = { ...basket };
copy.tags.push("sale");
console.log(basket.tags.join(" / "));
console.log(basket === copy);What gets logged?
Choose an output before opening the walkthrough, or check your answer in practice mode.
Reveal the answer and execution trace
new / sale
falseThe outer object is new, while the tags array is shared. Mutating that array is visible through both objects.
- Line 1. basket holds an object whose tags property points to an array.
- Line 2. The spread creates a second object and copies the tags reference.
- Line 3. push adds "sale" to the array referenced by both tags properties.
- Line 4. The original basket now reads both strings.
- Line 5. The two outer objects have different identities, so equality is false.
Reference: Shallow copies on MDN.