Sitemap
Tom Hall

Tom Hall

I help people turn their ideas into living web apps. Reach out, I want to hear about your idea. https://buildingyourideas.co

Generator Functions in Javascript (function*)

2 min readDec 6, 2018
Press enter or click to view image in full size

I was reading Eric Elliot’s tweet and saw something I didn’t know.

What was that function * (…)?

Turns out, that syntax defines a generator function. You can also create a generator function this way, but the first is shorter, so we’ll stick with that for now.

Instead of returns, the generator functions have yield. And instead of running the whole function at once, you can exit it and return later.

Get Tom Hall’s stories in your inbox

Join Medium for free to get updates from this writer.

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.

Next, we’ll see how this fits in with async 💪

Originally published at read.tomhalldev.com.

--

--

Tom Hall
Tom Hall

Written by Tom Hall

I help people turn their ideas into living web apps. Reach out, I want to hear about your idea. https://buildingyourideas.co