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

126
Visualizações
Using a function directly or by declaring it to a variable

I'm new to software development and trying to understand the basics of JavaScript. In the code below, if I write iterator.next() instead of charAt in "while", the result changes. Can you explain this to me why does it only return 1 when I type iterator.next directly?

  const str = '123';
  const iterator = str[Symbol.iterator]()

  let charAt = iterator.next()

  while (!charAt.done) {
    console.log(charAt.value)
    charAt = iterator.next()
    // output: "1"
    //         "2"
    //         "3"
  }

  const str = '123';
  const iterator = str[Symbol.iterator]()

  let charAt = iterator.next()

  while (!iterator.next().done) {
    console.log(charAt.value)
    charAt = iterator.next()
    // output: "1"
  }

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

0

It's easier to see if you have a longer string.

  const str = '12345678';
  const iterator = str[Symbol.iterator]()

  let charAt = iterator.next()

  while (!iterator.next().done) {
    console.log(charAt.value)
    charAt = iterator.next()
    // output: "1"
  }

Because you call next() in two different places inside the loop (as well as once outside the loop), every time you go around the loop, you advance two places.

about 4 years ago · Juan Pablo Isaza Relatório

0

  • u have used iterator.next() three times,
  • for the fitst time it returs 1, which u assign to charAt,
  • then in while loop condition iterator.next() returns 2, but u have not assigned it any where,
  • and because u have not updated your charAt value yet, it logs 1,
  • then iterator.next() returns 3, which u assign to charAt,
  • but in second pass of while loop iterator.next() returns {done:true}, and the control doesn't goes inside loop
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