How to Use Generators and Iterators in JavaScript
Iterating over data collections using traditional loops can quickly become cumbersome and slow, especially when dealing with massive amounts of data.
JavaScript Generators and Iterators provide a solution for efficiently iterating over large data collections. Using them, you can control the iteration flow, yield values one at a time, and pause and resume the iteration process.

Here you will cover the basics and internals of a JavaScript iterator and how you could generate an iterator manually and using a generator.
JavaScript Iterators
An iterator is a JavaScript object that implements the iterator protocol. These objects do so by having anextmethod. This method returns an object that implements theIteratorResultinterface.
TheIteratorResultinterface comprises two properties:doneandvalue. Thedoneproperty is a boolean that returnsfalseif the iterator can produce the next value in its sequence ortrueif the iterator has completed its sequence.

Thevalueproperty is a JavaScript value returned by the iterator during its sequence. When an iterator completes its sequence (whendone===true), this property returnsundefined.
As the name implies, iterators allow you to “iterate” over JavaScript objects such as arrays or maps. This behavior is possible due to the iterable protocol.

In JavaScript, the iterable protocol is a standard way of defining objects that you can iterate over, such as in afor…ofloop.
For example:

This example iterates over thefruitsarray using afor…ofloop. In each iteration it logs the current value to the console. This is possible because arrays are iterable.
Some JavaScript types, such as Arrays, Strings,Sets, and Maps, are built-in iterables because they (or one of the objects up their prototype chain) implement an@@iteratormethod.

Other types, such as Objects, are not iterable by default.
This example demonstrates what happens when you try to iterate over an object that is not iterable.
Making an Object Iterable
To make an object iterable, you have to implement aSymbol.iteratormethod on the object. To become iterable, this method must return an object that implements theIteratorResultinterface.
TheSymbol.iteratorsymbol serves the same purpose as@@iteratorand can be used interchangeably in “specification” but not in code as@@iteratoris not valid JavaScript syntax.
The code blocks below provide an example of how to make an object iterable using theiterObject.
First, add theSymbol.iteratormethod toiterObjectusinga functiondeclaration.
Next, you’ll need to access all the keys in the object you want to make iterable. You can access the keys using theObject.keysmethod, which returns an array of the enumerable properties of an object. To return an array ofiterObject’s keys, pass thethiskeyword as an argument toObject.keys.
Access to this array will allow you to define the iteration behavior of the object.
Next, you need to keep track of the object’s iterations. You can achieve this using counter variables.
You will use the first counter variable to keep track of the object properties and the second to keep track of the property’s children.
Next, you’ll need to implement and return thenextmethod.
Inside thenextmethod, you’ll need to handle an edge case that occurs when the entire object has been iterated over. To handle the edge case, you have to return an object with thevalueset toundefinedanddoneset totrue.
If this case is not handled, trying to iterate over the object will result in an infinite loop.
Here’s how to handle the edge case:
Next, you’ll need to access the object properties and their child elements using the counter variables you declared earlier.
Next, you need to implement some logic for incrementing the counter variables. The logic should reset thechildIndexwhen no more elements exist in a property’s array and move to the next property in the object. Additionally, it should incrementchildIndex, if there are still elements in the current property’s array.
Finally, return an object with thedoneproperty set tofalseand thevalueproperty set to the current child element in the iteration.
Your completedSymbol.iteratorfunction should be similar to the code block below:
Running afor…ofloop oniterObjectafter this implementation will not throw an error as it implements aSymbol.iteratormethod.
Manually implementing iterators, as we did above, is not recommended as it is very error-prone, and the logic can be hard to manage.
JavaScript Generators
A JavaScript generator is a function that you can pause and resume its execution at any point. This behavior allows it to produce a sequence of values over time.
A generator function, which is a function that returns a Generator, provides an alternative to creating iterators.
you could create a generator function the same way you’d create a function declaration in JavaScript. The only difference is that you must append an asterisk (*) to the function keyword.
When you call a normal function in JavaScript, it returns the value specified by itsreturnkeyword orundefinedotherwise. But a generator function does not return any value immediately. It returns a Generator object, which you can assign to a variable.
To access the current value of the iterator, call thenextmethod on the Generator object.
In the example above, thevalueproperty came from areturnkeyword, effectively terminating the generator. This behavior is generally undesirable with generator functions, as what distinguishes them from normal functions is the ability to pause and restart execution.
The yield Keyword
Theyieldkeyword provides a way to iterate through values in generators by pausing the execution of a generator function and returning the value that follows it.
In the example above, when thenextmethod gets called on theexamplegenerator, it will pause every time it encounters theyieldkeyword. Thedoneproperty will also be set tofalseuntil it encounters areturnkeyword.
Calling thenextmethod multiple times on theexamplegenerator to demonstrate this, you’ll have the following as your output.
You can also iterate over a Generator object using thefor…ofloop.
Using Iterators and Generators
Although iterators and generators may seem like abstract concepts, they are not. They can be helpful when working with infinite data streams and data collections. You can also use them to create unique identifiers. State management libraries such as MobX-State-Tree (MST) also use them under the hood.
The JavaScript community found a variety of ways to organize code into modules. Find out how the module system evolved in the JavaScript ecosystem.
You’ve been quoting these famous films wrong all along!
Your phone’s camera app doesn’t show this, so it’s easy to miss.
Tor spoiled me forever.
These films will leave you questioning humanity, but also wanting more.
Make sure you don’t miss these movies and shows before Netflix removes them.