The fill() method fills all the elements of an array from a start index to an end index with a static value.
In your case let matrix = new Array(2).fill(new Array(2).fill(0));
, the new Array(2).fill(0)
is evaluated once, its reference is provided to all the outer array. So, every outer Array is referencing the same inner array. Therefore, modifying a value is updating all other value.
You need to create different a new array reference for each row. The below code is creating a new inner array for every index.
let matrix = Array.from({length: 2}, _ => new Array(2).fill(0));
console.log(matrix);
matrix[0][0] = 1;
console.log(matrix);