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}
asked May 15, 2020 at 17:16
Mrudul Addipalli
6249 silver badges12 bronze badges
1 Answer 1
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());
answered May 15, 2020 at 17:29
loganfsmyth
162k31 gold badges349 silver badges259 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
x()to a new variable and then try,a = x(), a.next(), a.next()?