Nested loop query

So i was going through the “Caution when reinitializing Variables inside a loop” challenge. Following code

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

So i did a dry run as follows :
row =
newArray =
i = 0, j = 0 > row[0]
i = 0, j = 1 > row[0,0] > newArray[[0,0]]
i = 1, j = 0 > row[0,0,0]
i = 1, j = 1 > row[0,0,0,0] > newArray[[0,0],[0,0,0,0]]
i = 2, j = 0 > row[0,0,0,0,0]
i = 2, j = 1 > row[0,0,0,0,0,0] > newArray[[0,0],[0,0,0,0],[0,0,0,0,0,0]]

According to it, newArray should look like that, but actually it looks like
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]

I am not understanding what’s wrong in my dry run. Kindly assist.

before this, what you pushed to newArray was a reference to row, not a copy. So after you change row, newArray is now [[0,0,0]]

1 Like

Thank you!
Yeah, i pressed myself a bit more after posting the question and realised that the array “newArray” actually contains three array elements and all are infact the same “row” array. And since at the end the row array was [0,0,0,0,0,0] - it would be the same in all three array elements of newArray.

Ah, its tough to visualise this clearly at start

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.