[Could someone explain to me why the result is 18 zeroes if declaring the row as global variable? What knowledge should i have to understand this field? ]Use Caution When Reinitializing Variables Inside a Loop

Tell us what’s happening:
Could someone explain to me why the results is 18 zeroes if declaring the row as global variable?
What knowledge should i have to understand this field?

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
    
    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 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 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

When the row is pushed to the array, it is not a copy of the value inside that variable, but a reference to the array. The result is [row, row, row], and so if the row array is modified, the modification apply also to the references to the same array inside the newArray array

This challenge is there to understand this. To not declare an array as function-scoped in this case, if you need it copied various times.

you can also try looking at the code using this tool: http://pythontutor.com/javascript.html

You may also ask why [row, row, row] couldn’t be fine if each row has two zeros. Well, if you want to change one single element in the matrix you can’t, that’s the issue.

1 Like