0

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]);
}
2

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.