1

this code

let func = function *(){
    for (let i = 1; i < 5; i++) {
        yield i;
    }
}
let s = func().next();
console.log(s);
let s2 = func().next();
console.log(s2);

returns

Object {value: 1, done: false}
Object {value: 1, done: false}

so basically func yields first value all the time.

But when I change to

let f = func();
let s = f.next();
console.log(s);
let s2 = f.next();
console.log(s2);

it works as expected. Why assigning func to variable makes such a difference?

2
  • Because func() !== func()? Commented Apr 27, 2016 at 16:12
  • If it would behave differently, then every generator function could only be used once... Commented Apr 27, 2016 at 16:25

1 Answer 1

3

In your first bit of code, you are always creating a new generator instance. I've assigned those instances to separate variables to illustrate this more clearly:

// first generator instance
let g = func();
// first call to next on the first instance
let s = g.next();
console.log(s);
// second generator instance
let g2 = func();
// first call to next on the second instance
let s2 = g2.next();
console.log(s2);

Whereas in your second snippet, you keep iterating the same generator (assigned to the variable f):

let f = func();
// first call to next
let s = f.next();
console.log(s);
// second call to next
let s2 = f.next();
console.log(s2);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.