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
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);
It logs 7 7 — Array(3).fill(base) puts the same object reference in every slot, so when you do arr[1].count = 7 you’ve mutated the one object they all share.
If you want three separate objects, you need to create a new one per element (e.g. Array.from({ length: 3 }, () => ({ count: 0 }))).
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:
Fill bites people constantly because it looks like “make N copies” but it’s really “repeat this pointer N times”. I’ve seen it ship to prod and turn into a fun little heisenbug when one path mutates “its” element and magically changes the rest.
:: Copyright KIRUPA 2024 //--