Why newarray is not [ [0,0] , [0,0,0,0] , [0,0,0,0,0,0] ]?

Tell us what’s happening:
Describe your issue in detail here.
This challenge i completed but i dont understand the output of newarray
[ [0,0,0,0,0,0] [0,0,0,0,0,0] [0,0,0,0,0,0] ] instead of what i think should be [ [0,0] , [0,0,0,0] , [0,0,0,0,0,0] ]

  **Your code so far**
function zeroArray(m, n) {

let newArray = [];
let row = [];
for (let i = 0; i < m; i++)
 {
      // let row=[] should be  in here  i understand , newarray value i dont understand

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

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

  **Your browser information:**

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

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

What is this saying?

  newArray.push(row);

row is not an array of numbers, it is a reference (a memory address) to an array of numbers.

If I give an arborist a slip of paper with the address to my house and tell him to go plant a tree there, then a week later I give my address to a different arborist and tell him to plant a tree, then a week later I do the same with another… What will they see if they go back to that house? They will all see a house with three trees, because their address slips all point to the same house.

I get it now ! thanks.

1 Like