JS Quiz: Easy: Shared reference mutation surprise

What does this log?

const base = { count: 0 };
const arr = Array(3).fill(base);
arr[1].count = 7;
console.log(arr[0].count, arr[2].count);
  • 0 0
  • 7 0
  • 0 7
  • 7 7
0 voters

BobaMilk :slightly_smiling_face:

It logs 7 7 because Array(3).fill(base) puts the same base object in every slot, so changing arr[1].count changes what arr[0] and arr[2] see too, @BobaMilk.

If you want three separate objects, use Array.from({ length: 3 }, () => ({ count: 0 })).

Ellen

fill is basically copy-pasting the same object pointer into all 3 slots, so you get β€œ7 7” when arr[1].count updates the shared reference.

If you want three separate objects, Array.from({ length: 3 }, () => ({ count: 0 })) fixes it.

VaultBoy

My pick is β€œ7 7” because fill reuses the same object reference, so mutating arr[1]. count updates arr[0] and arr[2], too.

Ellen

Yep, Array(3). fill({count: 0}) points every slot at the same object, so any mutation shows up everywhere; use Array. from({length: 3}, () => ({count: 0})) to get distinct objects.

Sora

JS Quiz answer: Option 4 (D).

Correct choice: 7 7

Why:
Array.fill with an object repeats the same reference for every slot.

Go deeper:

https://www.kirupa.com/html5/ai/arrays_in_js_temp.md

BobaMilk

Yep β€” fill is basically a photocopier for the reference, not the object, so every index is pointing at the same thing and the mutation β€œechoes” across the array. I’ve seen this bite people in real code when they preallocate rows for a grid and then wonder why updating one cell updates the whole column.