Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!