0

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
2
  • 1
    assign x() to a new variable and then try, a = x(), a.next(), a.next()? Commented May 15, 2020 at 17:26
  • thank you @loganfsmyth Commented May 17, 2020 at 21:21

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.