Reputation: 624
I was learning javascript and if found new concept in function as generator functions As New Feature In ES6
var num=5;
function * x()
{
yield num++;
yield num*=num;
};
x().next();
{value: 5, done: false}
x().next();
It Should Return {value: 36, done: false} but returning
{value: 6, done: false} // It Should Return {value: 36, done: false}
Upvotes: 0
Views: 431
Reputation: 161677
Every call to x()
creates a new generator that will start at the beginning, so for
var num=5;
function * x()
{
yield num++;
yield num*=num;
};
console.log(x().next());
console.log(x().next());
is essentially identical to doing
var num = 5;
console.log(num++);
console.log(num++);
To get 36, you need to create a single generator and then call next()
on it, e.g.
var gen = x();
console.log(gen.next());
console.log(gen.next());
Upvotes: 2