I was working through the debugging section of the javascript course and managed to get through the challenges just fine. However, I couldn’t wrap my mind around why the push() function was giving the (intentionally) erroneous output that the challenge was presenting.
I have pasted the code below with an additional console.log() statement to track how the push statements are updating newArray:
//beginning of example code
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);
console.log(newArray); // checking number of zeroes in each pass of for loop
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
// end of example code
I would expect the final output of the matrix variable to be:
[ [0,0] , [0,0,0,0] , [0,0,0,0,0,0] ]
rather than the actual output of:
[ [0,0,0,0,0,0] , [0,0,0,0,0,0] , [0,0,0,0,0,0] ]
Why does the push statement update the previous element(s) of newArray on the second and third passes of the outer for loop?
EDIT: I’m not sure why the forum is putting only the inner for loop into a block and I’m not sure how to correct this. Thank you in advance for your patience as this is my first post on this forum.