Issue using Push within a For Loop

I don’t understand why the result of this code is:
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]

I would think that the following would actually be the result:
[ [ 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]

I found this in the exercise below:
Debugging: Use Caution When Reinitializing Variables Inside a Loop

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);

I was able to pass the exercise, but I just don’t understand the original results of the code.
Thanks!

The reason is because the code keeps pushing zeroes into the same array. When you write this line newArray.push(row); newArray doesn’t receive a copy of the values in row. Rather it stores a reference to row. Because of that, any subsequent changes to the array will also affect newArray.

The way the code is written now, newArray and matrix are storing three references to exactly the same array. You can confirm this by playing around in your console. If you pushing an item to matrix[0], you will find that matrix[1] and matrix[2] have a new item as well, because in fact all three are referring to the same array.

I hope this is helpful. Reply if you have any questions.

3 Likes

That makes sense now. I was thinking that it was storing a copy of the values of row rather than row itself. Thank you!