Question with Javascript

Hello World !
First, I apologize for my english that can be bad. I have a code that I can’t understand. Here it is :

function zeroArray(m, n) {

  let newArray = [];

  let row = [];

  for (let i = 0; i < m; i++) {

    for (let j = 0; j < n; j++) {

      row.push(0);

    }

    newArray.push(row);

  }

  return newArray;

}

let matrix = zeroArray(3, 2);

console.log(matrix);

It returns me this in the console :

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

I don’t understand why it returns this instead of that :

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

The row array contain [0, 0] at the first outside loop cycle, but the first value of newArray contain [0, 0, 0, 0, 0, 0].

Thank for helping !
Sam

Add a console.log statement to your inner for-loop and see what gets printed:

      for (let j = 0; j < n; j++) {
  
        row.push(0);
  
      }
      console.log(row)
      newArray.push(row);
  
    }

And, remember, arrays are mutable.

Thank for quick answer. I added a console.log statement and I see that the row array value is [0, 0] when the push() method is called. When does the value of newArray at index 0 changes and why?

The array row is declared outside of your loops, so with respect to those loops, row has a ‘wider’ scope and what you do inside of those loops affects row wherever it is located.

1 Like

I understand now. Thank for quick replies and have a nice day !

1 Like