Value of newArray?

Tell us what’s happening:
I have consoled logged and got a problem as follow

Can anyone tell me when the variable i =1 then the value of newArray is [[0,0,0,0] [0,0,0,0]] on output. I think the value of newArray should be [[0,0],[0,0,0,0]].

If i am wrong please correct 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);
console.log("At pass "+j+ ": ");
console.log(row);
console.log("After row
");

}

// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
console.log("
At pass "+i+ ": ");
console.log(newArray);
console.log("after col
")

}

return newArray;
}

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

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

Challenge: Use Caution When Reinitializing Variables Inside a Loop

Here is the pic

with arr.push(row) it is a reference to the row array that is added to the arr array, so any change to the row array will be reflected by its reference in the arr array

look at it with this, it is a good enough visualisation tool to understand what’s going on:

http://www.pythontutor.com/javascript.html

2 Likes

My question is different

Thanks for the link. I understood why it’s happening. Can you tell me why newArray and how newArray is keeping reference to row Array ?? Is this related to heap and let variable ? If yes please explain

My question is different pls read it again

Ohhhhhh thanks so much.

@DVGY Yes it is related to the let variable and the heap. When let newArr = [] is declared at the top, it is stored in the heap. and when the loop runs over and over again and when newArr is called, it will look in the heap for the key newArr and update the value.

2 Likes

Ohh i see very fluid explanation. Thanks