re: So you think you know JavaScript? VIEW POST


I think that's a really good and useful article

For the sixth answer, I made a bit another approach

obj[Symbol.iterator] = function*() {
  for (let key in this) {
    if (this.hasOwnProperty(key)) {
        yield this[key];

what do you think about that?
It makes me sure that I don't need to worry about new or old values


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

// calling next() again will continue the execution where it stopped the last time (inside for loop  😇); // { 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}
code of conduct - report abuse