Hello guys! I'm currently doing the 'JavaScript algorithms and data-structures' course here on freeCodeCamp and I'm stuck with this lesson: '**Use Caution When Reinitializing Variables Inside a Loop**, the main thing I don't understand is the behavior of the push method used for pushing the row array to newArray and why it first pushes this array:
[0,0]
But the next time it pushes row again to newArray it pushes:
[0,0,0,0]
and it overwrite the first position that have been already pushed on the previous step, and it does the same thing the last time the push method is used, so newArray ends up like this:
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
whereas in my mind, newArray should end like this:
[ [ 0, 0],
[ 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0 ] ]
I think the whole point is that I don't get why every time it pushes the row array with its current value but also changes the previous positions in the array.
Here's the code of the entire lesson:
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);
Thank you for your time and help . :slightly_smiling_face: