Can somebody explain this array behaviour to me?

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

    console.log(row);

    newArray.push(row);

    console.log(newArray);

  }

  return newArray;

}

let matrix = zeroArray(3, 2);

console.log(matrix);

-----------------------------------------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 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ] ]

shouldn’t it output this:

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

Arrays are mutable. When pushing row into newArray you are not adding there the actual values inside of the row at the time but the reference to the row array. When later row has added more elements it will be reflected as well inside of rows that were pushed to the newArray, because it’s literally a single array, accessed from different place.

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

i think i got it, when i change the row variable, it changes also in the newArray that contains it?

if you want a visual rapresentation you can see it happening with this tool:
http://pythontutor.com/javascript.html#mode=edit

1 Like