While trying to understand generator, instead of following:
function* powerSeries(number,power) {
let base = number;
while (true) {
yield Math.pow(base, power);
base++
}
}
let n = powerSeries(3,2)
n.next() // value: 9
n.next() // value: 16
...
I tried like:
function* powerSeries(number,power) {
let base = number;
yield Math.pow(base, power);
return base++ // was trying to understand what happens if using return
}
let n = powerSeries(3,2)
n.next() // value: 9
n.next() // value: 3 But how ????
I can understand post increment isn't being done because it's not inside a loop. So, it stays 3 for base. But how is it becoming 1 for power so it results in 3?
Acknowledged: Thank you everyone. I was confused that if I use return statement then it would still call yield.
1 Answer 1
From yield:
Description
[...]
A
returnstatement is reached. In this case, execution of the generator ends and anIteratorResultis returned to the caller in which thevalueis the value specified by thereturnstatement and done istrue.
function* powerSeries(number,power) {
let base = number;
yield Math.pow(base, power);
return base++ // was trying to understand what happens if using return
}
let n = powerSeries(3,2)
console.log(n.next().value); // 9
console.log(n.next().value); // 3
console.log(n.next().value); // undefined
1 Comment
Explore related questions
See similar questions with these tags.
base, notMath.pow(base, power)andbase === 3. There is no power of 1; nothing is being exponentiated at the second.next.poweris becoming 1? It's still 2, but after the singleyieldstatement (which produced the 9 you saw) it's never used again.yieldbe executed again? Tryyield ["yield", Math.pow(base, power)]; return ["return", base++]instead. Do you see twoyields? No; you get["yield", 9]and["return", 3].