Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda