DEV Community

Cover image for Generator Function
_Khojiakbar_
_Khojiakbar_

Posted on

1

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!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)