# Help me in :Use Caution When Reinitializing Variables Inside a Loop

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);

In this code In the inner loop
1.first iteration will push 2 0’s[0,0].
2.Second iteration will push 2 0’s .so it become 4 . 2 from the 1st iteration and 2 from this iteration[0,0,0,0].
3.Third iteration will push 2 0’s .so it become 6 .2 from the 1st iteration and 2 from 2nd iteration and 2 from this iteration[0,0,0,0,0,0].

so the console should show [[0,0],[0,0,0,0],[0,0,0,0,0,0]] but it’s showing [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]].why?

try looking at it with this: http://pythontutor.com/javascript.html#mode=edit

this add a reference to `row` inside `newArray`, so any changes to `row` will be reflected to the `newArray` array

you can see that they are all the same array doing this:

``````let row = [0,0,0];
let array = [row, row, row];
row[2] = 2;
array[1][1] = 1;

console.log(row); // [0, 1, 2]
console.log(array); // [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
``````
2 Likes

Thank you .