Why is this the default output for this code?

Tell us what’s happening:
Why is this the default output for this code?
The default output is
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]

But from my knowledge it should be like this:
[ [ 0,0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]

Your code so far


function zeroArray(m, n) {
  // Creates a 2-D array with m rows and n columns of zeroes
  let newArray = [];
  let row = [];
  for (let i = 0; i < m; i++) {
    // Adds the m-th row into newArray

    for (let j = 0; j < n; j++) {
      // Pushes n zeroes into the current row to create the columns
      row.push(0);
    }
    // Pushes the current row, which now has n zeroes in it, to the array
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0.

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

Remember that arrays are mutable. newArray.push(row); doesn’t push to newArray values which row contain at that time, but reference to the row. This means that when row is modified in further loops, that change will be also visible from the inside of newArray. The arrays in newArray and row are the same object, just being accessed using different names.

So the actual value of {row} is not being stored in the array but the array is referencing the value of {row} whenever it is called.

Exactly, the actual value is existing in different place.

Thanks for the help.