Not sure why rows are the same size in problem

Tell us what’s happening:
I understand that because the row variable is not being reinitialized, that the size of the row continues to grow beyond the desired two 0’s. What I don’t understand is why after the first time the row is pushed into the newArray, the size of that row (when i = 0 )changes in subsequent pushes in the newArray.

So what I expected to be output is
[ [0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0, 0] ]

  **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
  // 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 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

m = 3 and n = 2

On the first iteration in the for loop i = 0, and then second for loop starts and j = 0, the second for loop is setup to run as long as j < n so which means as long as it is less than 2. After the first iteration in the second loop , a 0 is pushed to row. Then the second loops starts the second iteration, now j = 1 and another 0 is pushed to row. Now the second loop ends because on the next iteration j would = 2 and the condition was j has to be less than n, ie j has to be less than 2. So we are now back in the outer for loop but still on the first iteration , so i is still 0 and now row (which now has 2 0s inside of it) gets pushed to new array.

Then here is where the issue was, that the problem was trying to get at, ie that row needs to be re initialized to an empty array.

If it is reinitalized, then when the first for loop moves on to the second iteration, ie i = 1, the same steps are repeated as above with regards to pushing the 0s into row,
so each time row will be an array with 2 0s .

Then finally new arr is returned . So you end up with a 3 x2 array of zeroes

I understand the solution to the problem. I did get their eventually. My question was in regards to the output before the solution is applied. I don’t understand why the output is what it is and not what I thought it would be.

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