Array(n).fill([]) shares one array
fill([]) evaluates [] once and puts that same array in every slot. Pushing to one pushes to all.
JavaScriptMutation and copying bugs
What it means
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.
Common causes
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.
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.
Other common errors
list.sort() returns NoneTypeError: 'str' object does not support item assignmentRuntimeError: dictionary changed size during iterationMutable default argument keeps old valuesChanging one row of a 2D list changes them allTypeError: Cannot read properties of undefinedReferenceError: Cannot access before initialization[object Promise] in output