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

How come the code that is given originally on this challenge leads to a result of
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
instead of
[ [ 0, 0, ],
[ 0, 0, 0, 0,],
[ 0, 0, 0, 0, 0, 0 ] ]
?

Because every array representing a row is the exact same array.

Yeah but the first time the row array gets pushed in it´s value is [0, 0], but the second time it gets pushed in it´s value now is [0, 0, 0, 0], why doesn´t the first array that got pushed in stay as [0, 0]? Does it somehow automatically update whenever the row array gets updated?

Pushing doesn’t keep it from being the exact same array. Everywhere you use that exact same array you will see the changes to that array

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