Tell us what’s happening:
Describe your issue in detail here.
Your code so far
I have a semi-related question. I just need a little clarification as to why, when the row array is a global variable outside of the nested for loop, the newArray still has three indices once the function returns newArray? Shouldn’t the function return once i = 2???
That is, why isn’t newArray:
[0, 0, 1, 1, 2, 2]
This to me makes sense because i = 2 , and the function call should be done. The function returns newArray.
Instead, newArray is actually:
[ [0, 0, 1, 1, 2, 2],
[0, 0, 1, 1, 2, 2],
[0, 0, 1, 1, 2, 2] ]
Why does it reset and continue to add to newArray? Shouldn’t the function return once i = 2 the first time?
function zeroArray(m, n) {
let newArray = [];
let row = [];
console.log("global variable")
for (let i = 0; i < m; i++) {
//let row = [];
//console.log("reset local")
for (let j = 0; j < n; j++) {
row.push(i);
console.log("j loop iteration i " + i);
}
newArray.push(row);
console.log("push i loop " + i)
}
console.log("return newArray")
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36
Challenge: Debugging - Use Caution When Reinitializing Variables Inside a Loop
Link to the challenge: