Don't understand output of function

Tell us what’s happening:
Describe your issue in detail here.

Why is the final array not [[0,0],[0,0,0,0],[0,0,0,0,0,0]]??? how does pushing a row change all values in the array?

  **Your code so far**

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);
}
return newArray;
}

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

Console output:
[ [ 0, 0 ] ]
[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]

  **Your browser information:**

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

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

You’ve forgotten to create a new row on each outer loop iteration. Right now the same row is being referenced on every loop.

1 Like

I understand why I am not getting the correct answer, but my question is why is the final result [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]] not [[0,0],[0,0,0,0],[0,0,0,0,0,0]].

Because you are reusing the same row. You keep modifying the row after pushing, so the row keeps changing in all three places.

1 Like

For another example of what’s happening:

const a = [1];
const b = a;

a.push(2);

console.log(a);
console.log(b);

What do you think will be logged here? If you said [1, 2], followed by [1], you’d be… incorrect! It’s actually [1, 2], and [1, 2]. Why? Because b holds a reference to the same array as a holds a reference to. Mutations to that array are visible when accessing via either a or b.

Basically, you’ve got an array that looks like [row, row, row], and in the end the array row references is [0, 0, 0, 0, 0, 0], so you get that three times.

2 Likes

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