This piece of code will print [1,2,3,4,5,6,7,8,9,10] on the console it means in every iteration arr.length change and this is reflected in the loop body also.
let arr = [1, 2, 3];
for (e of arr) {
arr.push(arr[arr.length - 1] + 1);
if (arr.length >= 10) break;
}
console.log(arr)
But here, The output will be [4,5,6] and that mean the shift() function is not considering the expansion of the array.
let arr = [1, 2, 3];
for (e of arr) {
arr.push(arr[arr.length - 1] + 1);
if (arr[arr.length - 1] >= 10) break;
arr.shift();
}
console.log(arr)
My question is why? I expected [8,9,10] output from second code
arr.shift()and usearr = arr.slice(-4,-1)insteadconsole.log(arr)immediately afterarr.shift();you'll see what's happening.