Debugging - Use Caution When Reinitializing Variables Inside a Loop

Hello everyone,
I’ve passed this section with the guide given. but I can’t really understand why:

let row = [ ];
that’s nested in outer loop will give result of

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

and when

let row = [ ];
is nested in the inner loop will makes the code properly working.

would appreciate an explanation on how these 2 work differently

  **Your code so far**
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
    let 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);

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36

Challenge: Debugging - Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

To understand the difference, change the bottom of your code to this:

let matrix = zeroArray(2, 1);
console.log('before the change')
console.log(matrix);
matrix[0][0] = 127
console.log('after the change')
console.log(matrix)

The issue is that when you create that array, you are allocating a spot in memory and saving the reference (memory address) to that in the variable. So, when you copy the array, you’re really just copying the address. If I give two people the address to the same house and then tell one person to go to that address and plant a tree, the other person sees the tree too because it’s the same house - just two copies of the same address.

This is a common source of confusion for learners - you’re in good company.

1 Like

I wrapped your answer in [spoiler][/spoiler] tags since it is a working solution to a curriculum problem.

Thanks Kevin! it helps me to understand more!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.