0

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.

asked Oct 1, 2019 at 17:21
10
  • 1
    You return base, not Math.pow(base, power) and base === 3. There is no power of 1; nothing is being exponentiated at the second .next. Commented Oct 1, 2019 at 17:23
  • Yeah, I'm knowingly doing that. And I already agree in my question that base is 3 as it's not inside loop. But how power is becoming 1? Commented Oct 1, 2019 at 17:23
  • Read my edited comment. Commented Oct 1, 2019 at 17:24
  • 1
    Why do you think power is becoming 1? It's still 2, but after the single yield statement (which produced the 9 you saw) it's never used again. Commented Oct 1, 2019 at 17:26
  • 3
    @gulcy "Ah, you mean yield is not being used but just return statement?" — Yes, of course. Why would yield be executed again? Try yield ["yield", Math.pow(base, power)]; return ["return", base++] instead. Do you see two yields? No; you get ["yield", 9] and ["return", 3]. Commented Oct 1, 2019 at 17:27

1 Answer 1

1

From yield:

Description

[...]

A return statement is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is the value specified by the return statement and done is true.

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

answered Oct 1, 2019 at 17:31
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I get it fully now.

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.