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

146
Vistas
JavaScript - What's the use of giving the choice of returning [Symbol.iterator]() in a [Symbol.iterator]()?

I built my code based on insights from this code:

https://github.com/davidflanagan/jstdg7/blob/master/ch12/Range.js

class SayHi {
  constructor (hi, repeat) {
    this.hi = hi;
    this.repeat = repeat;
  }
  [Symbol.iterator]() {
    let next = 1;
    let last = this.repeat;
    let hi = this.hi;
    return {
      next() {
        if (next<=last) {
          let now = next;
          next++;
          return { value: hi+now };
        }
        else {
          return { done: true };
        }
      },
      // What's the use of this??
      [Symbol.iterator]() {
        return this;
      }
    };
  }
}
let sayHi = new SayHi("HI", 3);
for(let x of sayHi) console.log(x);

I do not understand how this line of code works from the context of the whole program, because the program works without this code:

[Symbol.iterator]() { return this; }

How does it work? Why are we returning 2 functions for the outer Symbol.iterator? How do we invoke each of the functions?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is a relatively simple concept, something that I have recently learned myself. If you have a normal iterator object that rsturns an object without the [Symbol.iterator] then this would throw an error:

let data = [...iterator];

With this line, not only does the program not throw an error, but these two methods generate the exact same thing:

let data1 = [...sayHiInstance];
let data2 = [...sayHiInstance[Symbol.iterator]()];
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