As seen there is an array declared as numbers with three elements and variable counter. As in both the loops forEach and for. I am pushing new element to the array in each iteration. To my understanding both the loops should never stop as i am on every iteration increasing the size of the array.For loop behaves as expected and run indefinitely but forEach only prints three elements. i.e 1,2,3. Anyone can help with this.
let numbers = [1, 2, 3];
let counter = 0;
numbers.forEach((element) => {
numbers.push(counter + 1);
console.log(element);
});
console.log("After for each");
for (let i = 0; i < numbers.length; i++) {
numbers.push(i);
console.log(numbers[i]);
}
Array.prototype.forEachcaches the array length when started:Let len be ? LengthOfArrayLike(O)., and "Elements which are appended to the array after the call to forEach begins will not be visited by callbackfn".