Can't solve - Use Caution When Reinitializing Variables Inside a Loop

Can't solve - Use Caution When Reinitializing Variables Inside a Loop
0

#1

Tell us what’s happening:
I cannot solve the problem. I know that the problem is in the first for loop that produces 3 rows with 6 entries. Now I don’t get why there are 6 zeroes. Need explanation. Thanks.

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
    console.clear();
    console.log("starting array", newArray);
    for (let j = 0; j < n; j++) {
      // Pushes n zeroes into the current row to create the columns
      row.push(0);
    }
    console.log("ending row", row);
    // Pushes the current row, which now has n zeroes in it, to the array
    newArray.push(row);
  }
  console.log("Newarray", newArray);
  return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0.

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


#2

The problem is that the row variable is not being reset after each i loop. You need to change where the row variable is declared.


#3

I figured it out. Thanks.