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.
3 Answers 3
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());
Comments
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());
Comments
Because k is undefined the first time we run next()