[understandinges6] Generators

25 views
Skip to first unread message

Mohit Garg

unread,
May 5, 2017, 1:36:58 PM5/5/17
to Zakas Books
On Page 153 can you explain what do you meant by this?
The first call to next() is a special case where any argument passed to it is lost. Because arguments passed to next() become the values returned by yield, an argument from the first call to next() could only replace the first yield statement in the generator function if it could be accessed before that yield statement. That’s not possible, so there’s no reason to pass an
argument the first time next() is called.

function* iterator() {
  let x;
  let first = yield x + 12;
  let second = yield first + 1;
  yield second + 3;
}
let obj = iterator();
console.log(obj.next(1))   //{ value: NaN, done: false }


 I understand this is the way it's been specified but I can't understand why the value is NaN?

Nicholas Zakas

unread,
May 5, 2017, 3:44:00 PM5/5/17
to Zakas Books
Because x is undefined, and undefined + 12 is NaN.
--
You received this message because you are subscribed to the Google Groups "Zakas Books" group.
To unsubscribe from this group and stop receiving emails from it, send an email to zakasbooks+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Mohit Garg

unread,
May 5, 2017, 4:07:47 PM5/5/17
to Zakas Books
I understood that part, sir but can you explain this line?
arguments passed to next() become the values returned
by yield, 

Nicholas Zakas

unread,
May 5, 2017, 4:57:32 PM5/5/17
to Zakas Books
Sorry, I'm unsure how to describe that differently. Can you explain what part you find confusing?

Mohit Garg

unread,
May 6, 2017, 6:48:35 AM5/6/17
to Zakas Books
function* iterator() {
  let first = yield 12;
 let second = yield first + 1;
 yield second + 3;
}
let obj = iterator();
console.log(obj.next()) // 12
console.log(obj.next()) // NaN again

Why do we explicitly has to pass the value of first in the next? Since the first yield statement is executed shouldn't the value of first be 12 and automatically get assigned to the next yield statement?

Nicholas Zakas

unread,
May 16, 2017, 12:19:54 PM5/16/17
to Zakas Books
The 12 is returned by next(), but is not automatically assigned to first. Yield statements do not have values defined where they are used, the values are only defined by passing a value to next().
Reply all
Reply to author
Forward
0 new messages