Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Why this foreach loop not popping all the elements?

its only popping twice rather than 4 times

i tried for of loop but still same result.

var arr = [1, 2, 3, 4];
arr.forEach((val, index, io) => console.log(val, index, io.pop()))

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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}`);

about 4 years ago · Juan Pablo Isaza Report

0

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. !✌

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!