0

I am facing a issue while using yield in javascript generator.Let's have a look of my code first-

function* gen(a, b) {
 let k = yield a + b;
 let m = yield a + b + k;
 yield a + b + k + m;
}
let x = gen(10, 20);
console.log(x.next());
console.log(x.next());
console.log(x.next());

In the above code,at the first time when I run next(),it gave me a value of 30.But when I tried second time,in the second next(),it gave me a NAN value.It means,yield didn't assign the value of a+b in k.Instead it derectly move to the next line.But I think,it should assign value to k first.

What is happening here?Please let me know if you know.

Waldi
41.6k6 gold badges38 silver badges90 bronze badges
asked Apr 16, 2021 at 4:38

3 Answers 3

2

Inside a generator, the expression:

yield <someExpression>

evaluates to the value passed into the generator with .next, like this:

function* gen(a, b) {
 const valPassedIn = yield 'foo';
 console.log('valPassedIn', valPassedIn);
}
let x = gen(10, 20);
const containsFoo = x.next();
x.next(123);

In your code, since you aren't calling .next with anything, both k and m are undefined, so they can't be +d with anything (they'll produce NaN).

For what it sounds like you want, calculate the sum, yield it, and assign it to k separately.

function* gen(a, b) {
 let k = a + b;
 yield k;
 let m = a + b + k;
 yield m;
 yield a + b + k + m;
}
let x = gen(10, 20);
console.log(x.next());
console.log(x.next());
console.log(x.next());

answered Apr 16, 2021 at 4:41
Sign up to request clarification or add additional context in comments.

Comments

0

k and m remain undefined as the assignment to them is after the yield has completed. Assign value to the respective variables before the yield

function* gen(a, b) {
 k = a + b;
 yield k;
 m = a + b + k
 yield m;
 yield a + b + k + m;
}
let x = gen(10, 20);
console.log(x.next());
console.log(x.next());
console.log(x.next());

answered Apr 16, 2021 at 4:47

Comments

0

Because k is undefined the first time we run next()

answered Apr 16, 2021 at 4:48

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.