Use Caution When Reinitializing Variables Inside a Loop: Question

Hello.

I have a question about “Step 11” of the “Debugging” section of “Javascript Algorithms and Data Structures” (https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop).

The exercise problem consists of me fixing the code for the function zeroArray(m, n) so that it returns an array with m rows and n columns.

Here is the code given to fix:

function zeroArray(m, n) {

  let newArray = [];
  let row = [];

  for (let i = 0; i < m; i++) {

    for (let j = 0; j < n; j++) {
      row.push(0);
    }

    newArray.push(row);
  }

  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);

I understand that the issue comes from not reinitializing the row variable within the outer loop, and I know how to fix the code so that it returns the correct result, which would be to add row = []; directly “under” the outer for loop.

However, my question is about the output of the incorrect code above.

Why does console.log(matrix); display

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

instead of

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

My reasoning (which is obviously flawed):

\*
1) i : 0
row : [0, 0]
newArray : [[0, 0]]

2) i : 1
row : [0, 0, 0, 0]
newArray : [[0, 0], [0, 0, 0, 0]]

3) i : 2
row : [0, 0, 0, 0, 0, 0]
newArray : [[0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
*\

However, it seems as though when row gets updated by adding new zeros within the inner loop, the array(s) within myArray are simultaneously updated as well. Does this mean that the rows already created within myArray are still referenced as the variable row?

Hope I was able to word my confusion and reasoning in a clear way.

Any help is appreciated! Thank you as always.

If m is 3 and n is 2 then the outer for loop runs three times and the inner for loop runs two times. The inner for loop pushes 0 on the row twice, and this is done three times. So you end up with six zeros in the row.

2 Likes

I understand that the final row ends up with six zeros after running through all the loops, but I was wondering why the array(s) already added to myArray in previous loops get(s) updated when row.push(0) is executed within the inner loop.

Aaaand… as I am writing this, I’ve just realized that newArray.push(row) means that previous arrays are all still accessible by the variable row, thus updated every time row.push(0); is executed within the inner loop. Missed an obvious point; sorry about that! :sweat_smile:

Thank you so much for the quick reply, as always, @bbsmooth!

1 Like

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