Use Caution When Reinitializing Variables Inside a Loop new

Tell us what’s happening:

I have looked at some examples but I must confess to being baffled by this challenge. I don’t know where to start. Can anyone assist?

Sorry for posting so many questions BTW.

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 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/

The problem the challenge is trying to focus on is the variable initialization in the wrong place. You have the row array initialized out of both the loops.

If you think about the role of the variable ( it’s an array created to contain all the items in a single row ) and you look at the comments it will be easier to understand what you have to do to pass the challenge^^

Extra hint:

You can do this without writing a single character: just copy-pasting something of the actual code :wink:

Good luck!

1 Like