JavaScript Generators and their Use Case: Everything Yield Need To Know

Masifulhaque
2 min readFeb 16, 2021

--

JavaScript generators is an amazing and brilliant concept; yet it’s very confusing when to use them. They let us write infinite loops that terminate. The yield values from functions before they finish and build lazy data structures. The magic lies in the ability of generators functions to be paused and then resumed again.

Regular functions return only one, single value (or nothing). Generators can return multiple values, one after another, on-demand. They work great with iterables, allowing to create data streams. To create a generator, we need a special syntax construct: function*.

Generator functions behave differently from regular ones. When such function is called, it doesn’t run its code. Instead it returns a special object, called “generator object”, to manage the execution. The main method of a generator is next(). When called, it runs the execution until the nearest yield<value> statement. Then the function execution pauses, and the yielded value is returned to the outer code.

Now let’s turn our focus on ‘where’ –

  • Lets say we want to play and pause loops if someone hit a pause button on an animation. Generators can be used with this for loops which need to be paused and resumed at a later time.
  • We want an infinitely looping array for things like carousels or lists of data which wrap around. Generators can be used for infinitely looping over an array and having it reset to the beginning once it’s done.
  • We want to iterate over objects to check if any of its properties include a specific value. We use generators by creating iterables to use in ‘for of ‘ loops from non-iterable objects using [Symbol.Iterator]; get the array and then check with .includes().
  • to loop through structures where we’d normally need to keep track of multiple variables at a time.

How does yield work JavaScript?

The yield keyword pauses generator function execution and retains the value of the expression after the yield keyword is returned to the generator’s caller. yield can only be called directly from the generator function that contains it. It cannot be called from nested functions or from callbacks. Once paused on a yield expression, the generator’s code execution remains paused until the generator’s next() method is called. Each time the generator’s next() method is called, the generator resumes execution.

Read the full article here -https://asifulhaque.com/what-is-javascript-generators/

javascript generators

--

--

Masifulhaque

An adaptable and responsible graduate with BSc degree(CSE, BUET) and MBA(IBA); working as a software developer.