How To Transform JavaScript Functions Into Memory-Efficient Generators

Start using yield in JavaScript

Artturi Jalli
Better Programming
Published in
5 min readJul 22, 2021

--

Hot-air balloons
Photo by Ricardo Rocha on Unsplash.

In JavaScript, yield is used to pause the execution of a function. When the function is invoked again, the execution continues from the last yield statement.

A function that yields values is a generator. Here is an illustration of running a function vs. running a generator function:

Diagram of functions vs. generators in JavaScript
Functions vs generators in JavaScript

A generator returns a generator object, which is an iterator. This object generates one value at a time and then pauses execution. It does not store values, so it’s memory-efficient.

How To Turn a Function Into a Generator

To turn a function into a generator:

  • Add an asterisk symbol (*) after the function keyword.
  • Use yield instead of return.

Example

Let’s create a normal function, square(), that squares an array of numbers:

Result:

[1, 4, 9, 16, 25]

Let’s turn this function into a generator.

Instead of adding the squares into an array, yield them one at a time:

Output:

: [object Generator]

You don’t get an array of squared numbers as a result yet. This is because the result, squared_numbers, is a generator object. This generator object has not done any computation yet.

Let’s take a look at how you can get squared numbers from the generator object.

--

--