codecks.

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.

  1. new / sale
    false
  2. new
    false
  3. new / sale
    true
  4. new
    true
Reveal the answer and execution trace
new / sale
false

The outer object is new, while the tags array is shared. Mutating that array is visible through both objects.

  1. Line 1. basket holds an object whose tags property points to an array.
  2. Line 2. The spread creates a second object and copies the tags reference.
  3. Line 3. push adds "sale" to the array referenced by both tags properties.
  4. Line 4. The original basket now reads both strings.
  5. Line 5. The two outer objects have different identities, so equality is false.

Reference: Shallow copies on MDN.