DEV Community

Cover image for Generator Function
_Khojiakbar_
_Khojiakbar_

Posted on

Generator Function

A generator function in JavaScript is a special type of function that can pause its execution and resume later. This makes them great for handling sequences, such as generating a series of values.


Let's imagine a generator function as a funny, laid-back librarian who hands you one book at a time instead of all at once.

Here's how it works:

  1. Define the Generator Function: It starts with function* instead of function. This tells JavaScript that this function is special and can pause.

  2. Use yield: Inside the function, use yield to hand out values one at a time, like the librarian handing out books.

  3. Call the Generator: When you call the generator, it doesn't run the code right away. Instead, it returns a "generator object" which you can ask for values from.

  4. Get Values with .next(): To get the next value, use the .next() method on the generator object.

Here’s a simple and funny example:

Image description

Breakdown of the Funny Library Story:

Define the Librarian:

Image description

The function* keyword tells JavaScript that bookLibrarian is a generator function. The librarian (generator) has three books (values) to give out one at a time.

Calling the Librarian:

Image description

This doesn’t hand out any books yet. It just prepares the librarian to start handing out books when asked.

Getting Books One at a Time:

Image description

Each call to librarian.next() makes the librarian hand out the next book. When there are no more books, the librarian returns undefined.

So, in essence, a generator function is like a librarian who gives out one book at a time, and you have to keep asking for the next one until there are no more books left!

Top comments (0)