I'm new to javascript and I've been going through some exercises but I can't figure out why this code works like this,
let newArray = [];
let arr1 = [];
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 2; j++) {
arr1.push(0);
//console.log('Arr1:',arr1);
}
newArray.push(arr1);
//console.log('New Array:', newArray)
}
console.log(newArray);
According to me, this block of code should output [[0,0][0,0,0,0]] but the real output is [[0,0,0,0][0,0,0,0]].
I tried console logging after every iteration(by removing the comments) and I can't seem to find where it goes wrong. It seems like it all goes well until the last log. I'd appreciate your help.
newArraycontainsarr1twice. After the firstnewArray.push(arr1), the value that was just added tonewArrayis a reference toarr1not the values ofarr1. After that, when you modifyarr1, the first value innewArrayis also modified.arr1once, if I modify it after that, the pushedarr1is modified too?newArray.push([...arr1]).[...arr1]will create a new array that contains all the value ofarr1at that point.