I was reading Eric Elliot’s tweet and saw something I didn’t know.
What was that function * (…)?
Instead of returns, the generator functions have yield. And instead of running the whole function at once, you can exit it and return later.
This is what I mean:
We have a generator function called track. Then we assign it with the values 3 and 4 to the variable a. Then we can step through the yields using next() and log the value. This generator function is returning an iterator object. That’s how we can call next() on it. The next() method returns an object that has value and done. Like this:
As you’d guess, done says whether that was the last yield or not, and value is what’s returned from the resolved expression. You can also use yield* func1() to delegate the yield expression to another generator object. If you keep trying next() after the generator has finished, you’ll get:
value: undefined, done: true}
If you want to end the generator, put a return in there and it’ll end.