DEV Community

Discussion on: So you think you know JavaScript?

Collapse
 
aman_singh profile image
Amandeep Singh • Edited

This is a beautiful approach Max. 😀

For other people to understand, let me explain Max's approach here:

// an iterator object is returned
 const iterator = ob[Symbol.iterator]();

 // calling next method will execute the body till first yielded expression (yield this[key])
// and returns a value of {value: 'x', done: false}
iterator.next(); 

// calling next() again will continue the execution where it stopped the last time (inside for loop  😇)
iterator.next(); // { value: 'y': done: false}

// and thus the process will continue till done is *true*

The takeaway is:

  • calling a generator function doesn't execute its body; an iterator object is returned.
  • generator function's body is executed until the first yield expression when iterator's next() is called, and the value returned will be of the shape {value: 'x', done: true}