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.