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

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

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