Your code works as expected.
Array.pop() method removes the last element from an array and returns that element. This method changes the array from which it has been called.
Array.pop() returns the removed element from the array.
When the iteration index is 0, it will iterate through the array [1, 2, 3, 4], it removes 4 on the first iteration, which makes the length of the array as 3.
When the iteration index is 1, iteration will be done on Array [1, 2, 3] and it removes 3 from this array.
Now the length of Array is 2 and the iteration has already completed twice and the loop exits.
Thats why your loop excecutes only twice.
const arr = [1, 2, 3, 4];
arr.forEach((val, index, io) => {
console.log(`Iterating ${index + 1}`);
console.log(val, index, io.pop());
console.log(`Array After Iteration ${io}`);
});
console.log(`Final Array ${arr}`);
var arr = [1, 2, 3, 4];
arr.forEach((val, index, io) => console.log(val, index, io.pop()))
Your code is doing what it should
val | index | io.pop() | Modified Array
1 0 4 [1, 2, 3]
2 1 3 [1, 2]
// since it already reached at 2 no other element needs to be traversed and hence iteration stops.
Each time you are logging it is removing the last element of the array and moving the forward as well.
The callback is executed only for the elements that are present in the array and hence as your elements are being removed with every log you remain with two elements and hence it runs only two times.
Hope This helps. !✌