Array(n).fill([]) shares one array
Array(n).fill([]) shares one array in JavaScript means fill([]) evaluates [] once and puts that same array in every slot. Pushing to one pushes to all.
How do I fix Array(n).fill([]) shares one array?
In JavaScript, Array(3).fill([]) creates one array and puts that same array in every slot, so pushing to one slot shows up in all of them. Use Array.from({ length: 3 }, () => []) instead, which calls the function once per slot and creates a new array or object each time.
- 1. fill() with [] or {}Search for .fill([]) or .fill({...}). Any object or array passed to fill() is shared.
- 2. Use Array.fromWrite Array.from({ length: n }, () => ({ done: false })) for objects. Note the parentheses around {}.
- 3. fill() is fine for primitivesfill(0), fill("") and fill(false) are safe, because numbers, strings and booleans cannot be changed in place.
What does Array(n).fill([]) shares one array mean?
fill() copies the value you give it into each position. For numbers and strings that is fine. For an array or object, every position holds a reference to one shared object.
Why does Array(n).fill([]) shares one array happen?
1. Creating a list of empty groups
Every group is the same array.
Breaks
const teams = Array(3).fill([]);
teams[0].push("a"); // all three now contain "a"Works
const teams = Array.from({ length: 3 }, () => []);2. Filling with an object
Same trap with {}.
Breaks
const rows = new Array(5).fill({ done: false });Works
const rows = Array.from({ length: 5 }, () => ({ done: false }));How to find it in your own code
Use Array.from({ length: n }, () => newValue) so the factory function runs once per slot. Keep fill() for primitives such as 0, "" or false.
Practise mutation and copying bugs
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.