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