What is going on in these for loops?

Tell us what’s happening:
I understand for the challenge I need to add row = in the first loop to reinitialize it. What I don’t get is why before fixing the matrix it is calculating to:

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

If I’m understanding the code snippet and how push() works correctly, newArray.push(row) is being invoked 3 times, in the outer loop and each time row is being pushed into newArray. The first time it would push [0,0] then, [0,0,0,0], and last [0,0,0,0,0,0] so why isn’t the output:

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

Thanks in advance!

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
  // Pushes the current row, which now has n zeroes in it, to the array
return newArray;

let matrix = zeroArray(3, 2);

Your browser information:

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

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

for how arrays work, it is pushing a reference to row
so the array at the end is [row, row, row], whatever the value of row at the end, that’s what appear inside newArray

1 Like

you can look at the code with this tool to see it visualized:


1 Like

@ilenia THANK YOU! I did not realize JavaScript referenced arrays (which to my understanding are objects in JavaScript) like that! I’m 1,000,000 times sure you just saved me a bunch of headaches and heartaches from my future programs. Thank you again and for the new tool as well.

it does the same with objects, in case you didn’t know

1 Like