JavaScript Generator Functions

JavaScript Generator Functions

What is meant by generator Function?

A generator function is a special type of function in JavaScript that allows pausing and resuming its execution during runtime. Generator functions are defined using the function*  and they use the yield keyword to pause the function's execution and produce a value.

Basic Syntax of Generator Functions:

  • The function* keyword indicates that this is a generator function.
  • Inside the generator function body, the yield keyword is used to pause the function and produce a value to the caller.
  • You can either use function* generatorFunc() {...} or function *generatorFunc(){...} to create them.

Using Generator Functions:

To use a generator function, we need to call it and obtain an iterator object. The iterator object has two essential methods: next() and return(). Let's understand these methods:

The next() Method :

The next() method is used to resume the execution of a generator function from where it was paused. It returns an object with two properties: value and done.

  • The value property contains the value produced by the yield statement.
  • The done property is a Boolean indicating whether the generator has completed (true) or is still running (false).

Example:

The return() Method:

The return() method allows us to force a generator to complete before it reaches the end. It can take an optional argument that will be returned as the final value of the generator.

Example:

Iterating Over Generator Functions:

Generator functions can also be used to create custom iterators. An iterator is an object that implements the iterator protocol, which requires the presence of a next() method that returns an object with the properties value and done.

Example:

In the above example, the counter() generator function creates an infinite sequence of numbers. We can iterate over this sequence using the next() method of the iterator.

Read more