Reputation: 27323
So this code was published on same places before as an example of generators in es6:
function *addGenerator() {
var i = 0;
while (true) {
i += yield i;
}
}
var gen = addGenerator();
console.log(gen.next().value);
console.log(gen.next(3).value);
console.log(gen.next(5).value);
Which gives: 0, 3, 8
.
What I don't get is why this += yield i
works. I guess it's because we wait until we get the next value, and if you pass something in next()
it's an implicit return. So far so good. But why is the name of the var i
?
If I do:
function *addGenerator() {
var i = 0;
var j = 0;
while (true) {
i += yield j;
}
}
It does not work, so there is something special about that var... Who knows?
Upvotes: 0
Views: 101
Reputation: 35950
In second example you'll get 0 0 0
as an output, because gen.next().value
is the value of j
variable - and this is 0 - you don't assign to it in a loop.
General form of yield
keyword can be seen as something like:
var passedToNext = yield returnThisAsNext_value;
Upvotes: 2