Some weird things about array, loop and "console.log" on chrome

The problems come from the challenge Debugging: Use Caution When Reinitializing Variables Inside a Loop
The challenge itself is easy. You need to reinitialize the array “row” when “i” increased. But the wrong result is confusing:
I thought it would be [[0,0],[0,0,0,0],[0,0,0,0,0,0]].

I changed code to this:

function zeroArray(m, n) {
			let newArray = [];
			let row = [];
			for (let i = 0; i < m; i++) {
				for (let j = 0; j < n; j++) {
				console.log("the row is",row);
				console.log("the rowlength is",row.length);
				console.log("the newArray before push is",newArray);
				console.log("the newArraylength is",newArray.length);
				console.log("the newArray after push is",newArray);
				console.log("the newArraylength is",newArray.length);
				console.log("\nnext loop\n\n")

		let matrix = zeroArray(3, 2);

The result is:

When I expand arrays, “row” and “newArray” are strange. There are two differernt length of “row” and “newArray” . I expand arrays in first loop like this:

Beside of the length, it looks like that the newArray has already been pushed zeros in other rows during first loop, even before the code executed.

if you use a tool like you will see it better

but what happens is that you are adding to the outer array a reference to row (not a copy), meaning any change to that one is also reflected in the outer array

1 Like

The tool is very useful! Thank you for your recommendation. I‘ve bookmarked it.
But I still can’t understand clearly why “newArray” changed at the start of second loop.
What do you mean “reference"?

Oh! I see. The first element of “newArray” is not the value of an array but the reference to the array “row” actually, so when “row” changed, “newArray” changed.
Thank you!

I see you have found the rapresentation to the right, good!

good job with understanding it