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

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

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 Denunciar

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 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