Why .push( ) here replaces previous items

Tell us what’s happening:

Can anyone tell me why the .push() function here replaces the previous row it pushes into the newArray please? As far as I know, .push() only adds the elemente(s) in the () at the end?

  **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 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36 Edg/98.0.1108.50

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

push() isn’t replacing anything. The problem is that you only have one row array, so that one array keeps getting bigger and bigger.

1 Like

You’re just pushing it into the same row. There needs to be a row for every iteration of the outer loop, not just one.

1 Like

As far as i understand, the newArray here should be equal to the following after each time the .push adds another row at the end:
[ [ 0, 0 ] ]
[ [ 0, 0 ], [ 0, 0, 0, 0 ] ]
[ [ 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ] ]

I can vagouly see the logic of the out put but please helping me out what i am missing please.

This is the exact same row every singe time.

Still the same row. You never change which array you are using.