Use Caution When Reinitializing Variables Inside a Loop mine

Tell us what’s happening:
helo plz i need a summary for the code below

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
    row=[];//plz i want to knw why row=[]; works and not 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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop/

If you use newArray = [] you are pushing things in newArray but then at next iteration you are emptying it. If you keep emptying it, it will never be what you want it to be.

You can see what happens in your code with this tool:
http://pythontutor.com/javascript.html#mode=edit

1 Like

thanks for d link i didnt knw stuff like dat exist