0

I'm trying to learn about generator functions in javascript and am experimenting with using a for..of loop in order to iterate over my yield statements. One thing I noticed is that the function terminates after the final yield statement and does not attempt to execute the return statement. If I were to create a generator object and call generator.next() 4 times, the return statement would trigger and we would see the associated generator object. Would anyone have any idea what's going on under the hood to cause this behavior?

Thanks!

function* generator(){

    yield 1
    yield 2
    yield 3

    return "hello there"
}


for (const value of generator()){
    console.log('value', value)
}
1
  • check the done inforamation, read the doc! Commented Oct 6, 2022 at 22:02

1 Answer 1

1

the function terminates after the final yield statement and does not attempt to execute the return statement

This is wrong, the return statement is executed, which is easy to see with

function* generator() {
    yield 1
    yield 2
    yield 3
    console.log('returning')
    return "hello there"
}

for (const value of generator()) {
    console.log('value', value)
}

And indeed the next method is called 4 times by the loop:

function* generator() {
    yield 1
    yield 2
    yield 3
    return "hello there"
}
const iterator = {
    state: generator(),
    [Symbol.iterator]() { return this; },
    next(...args) {
        const res = this.state.next(...args)
        console.log(res)
        return res
    },
}
for (const value of iterator) {
    console.log('value', value)
}

However, the return value, not being a yielded value, marks the end of the iteration and does not get to become a value in the for loop body, which only runs 3 times. If you wanted it to run 4 times, you'd need to yield 4 values.

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.