Use caution, could anyone give a deep technical explanation to this challenge?

hi guys
1- my question is why we need to reinitialize the raw variable inside the for Loop if it is declared before?

2- and why the row.push(0) push more than one 0 (six zeros before) without using iteration like I or j?

3- because if you want to push two zeros you can do it that way row.push(0) * j

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
    row = [];
    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);

Right now I have just the time to suggest you this tool, play with the code and see what changes if you change some things, like if you don’t reassing row variable
http://pythontutor.com/javascript.html

I think you meant row variable. Technically, you don’t even have to declare it before the 2nd loop. You do need to initialize it inside the 2nd loop so that it resets it back to an empty array. Otherwise the 2nd for loop would end up creating a large array which would grow through out all the main array elements.

The following is fine:

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

However, if you only initialized it outside the 1st for loop like below:

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

it would result in the following array, which is not what you want at all

[ [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ] ]

It is using the i and j but just for the purposes of iteration and not using the actual values.

What exactly do you think row.push(0) * j would do? If you are not sure, then test it for yourself.