Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda