That’s because in case of array1
it contains three arrays, but all three of them point to the same reference variable, that was evaluated when new Array(n)
was executed:
var array1 = new Array(n).fill(new Array(n));
So when the for
loop runs over array1
it is setting the value of the same array reference, while in case of array2
those three arrays are different reference variables.
Here’s a slightly modified version of your snippet. Notice the entries into console when the value of array1
‘s element is being changed. In case of array1
all three child arrays are changing, while in case of array2
the array referenced under the loop using index i
is the only one that changes.
function test(n = 3) {
array1 = new Array(n).fill(new Array(n));
array2 = [
[undefined, undefined, undefined],
[undefined, undefined, undefined],
[undefined, undefined, undefined]
];
document.getElementById("output").innerHTML = JSON.stringify(array1) + " (array 1) <br/>" + JSON.stringify(array2) + " (array 2)<br/><br/><i>The commas with nothing in between mean undefined.</i><hr/>";
for (i = 0; i < n; i++) {
array1[i][0] = i;
array2[i][0] = i;
console.log("Array 1: " + JSON.stringify(array1));
console.log("Array 2: " + JSON.stringify(array2));
}
document.getElementById("output").innerHTML += JSON.stringify(array1) + " (array 1) <br/>" + JSON.stringify(array2) + " (array 2)<br/><br/><i>The commas with nothing in between mean undefined.</i><hr/>";
}
<button onclick="test();">Press to test</button>
<br/><br/>
<div id="output"></div>