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

179
Visualizações
Javascript for in loop and pop()

I just learnt the arrays for-of loop which iterates through each elements of an array and I used it to empty an array using pop() which removes the last element of an array but this isn't working.

let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of skills) {
  skills.pop();
}
console.log(skills); // HTML , CSS, Javascript

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The array iterator is like a live collection; if the array changes while being iterated over, the next item(s) returned by the iterator will reflect the change. As you can see in the link above, it works by incrementing an index that starts from 0 until the length of the array has been reached.

for (let skill of skills) {

is, in this situation, nearly equivalent to

for (let i = 0; i < skills.length; i++) {
  const skill = skills[i]

The array iterator doesn't return a static amount of items determined when the iterator is initially called; the next item to be returned is determined on the fly on each iteration. So if you .pop an item from the array inside an iteration, there will be one fewer iteration overall than if you hadn't popped, unless you're already at the end of the array.

If there are 6 items in the array - as there are here - then you'll pop 3 times, and there will be 3 fewer iterations than the number of items - resulting in a total of 3 iterations total, and 3 items removed.

If you turned the array into one that didn't change while iterating over it, .pop would work. (This isn't a recommendation - there are better ways to empty an array - just for illustration, to make what's going on clearer.)

let skills = ["HTML", "CSS", "Javascript", "SASS", "Bootstrap", "Tailwind"];
for (let skill of [...skills]) {
  skills.pop();
}
console.log(skills); // empty

This works because [...skills] creates a separate array whose elements don't get removed when skills.pop is called.

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