I’ve passed the Use Caution When Reinitializing Variables Inside a Loop
challenge by simply unfolding the loops. Then I wanted to see how other people and FCC solved it, because my solution felt like cheating
Needless to say, FCC and other campers solved it as it was instructed: by reinitializing the row
variable. So, I wonder, whether I’ve actually found another way around to create matrix arrays or just fell into a “loophole” in the tests, and it hides that my solution is actually wrong?
function zeroArray(m, n) {
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
newArray.push(row);
}
for (let j = 0; j < n; j++) {
row.push(0);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
I think, I understand, why we need to reinitialize the row
before the column loop.
Thanks to this answer, I figured that, when we don’t reset and basically declare new row
to push n-amount of zeros, it’ll drag around the same row
in every iteration of both loops.
My reasoning is that, before fixing the initial code, we push the row
in newArray
and it’s like newArray=[row, row, row]
where row
is the same variable that we change in the nested loop, so, when we change row
, all nested arrays change too.
And we get
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
and not
[ [ 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
Initial code with consoles that helps to see it:
function zeroArray(m, n) {
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
console.log(newArray);
for (let j = 0; j < n; j++) {
row.push(0);
console.log(row);
}
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
That displays mid-results:
[]
[ 0 ]
[ 0, 0 ]
[ [ 0, 0 ] ]
//here it remembers the previous zeros and adds more
//because it still operates with the same variable
[ 0, 0, 0 ]
[ 0, 0, 0, 0 ]
//it changes all row arrays in the newArray
// because - again - they're all the same variable
[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
[ 0, 0, 0, 0, 0 ]
[ 0, 0, 0, 0, 0, 0 ]
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
So when we declare the row
back to []
before going to the inner loop, it means that we operate with a new row
variable that happens to have the same name for our convenience, right?
It’s the same newArray=[row, row, row]
but this time every row
is created anew before we push zeros into it and then add it to the newArray
.
And in my solution I’m not reinitilizing the row
. It remembers newArray
as an array that holds three values of the same variable - row
, that will be later changed by adding n
zeros in the second loop.
(Also for some cryptic reason, it reminds me the variable’s scope, but it might as well just be an association.)
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0
Challenge: Use Caution When Reinitializing Variables Inside a Loop
Link to the challenge: