OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Deep dive into JavaScript's Iterators, Iterables and Generators

Nwakor Chidinma Favour
August 8th, 2022 · 5 min read

The default operations like for...of loop in JavaScript are powered behind the scene by the concepts of Iterators, Iterables, and Generators. These concepts serve as the protocol for iterating over data structures provided by JavaScript, such as the for...of loop, used to traverse the elements of specific data structures one by one.

Throughout this article, we’ll discuss and explore these concepts and learn how to implement them within your next JavaScript project.

Symbols for iterators

But before we explain these concepts, we’ll take a short discovery on the JavaScript built-in method, Symbol.iterator(), which serves the unit block on implementing custom iteration in JavaScript.

1// syntax
2Symbol.iterator() // Symbol(Symbol.iterator)

The concept of an Iterable is any structure that has the Symbol.iterator key; the corresponding method has the following behavior:

  • When the for..of loop begins, it first looks for errors. If none are found, it then accesses the method and the object that the method is defined on.
  • The object will then be iterated in a for..of loop manner.
  • Then, it uses the next() method of that output object to get the next value to be returned.
  • The values given back will have the format done:boolean, value: any. The loop is finished when done:true is returned.
1let list = {
2 start: 2,
3 end: 7,
4};
5
6list[Symbol.iterator] = function () {
7 return {
8 now: this.start,
9 end: this.end,
10 next() {
11 if (this.now <= this.end) {
12 return { done: false, value: this.now++ };
13 } else {
14 return { done: true };
15 }
16 },
17 };
18};
19
20for (let i of list) {
21 console.log(i);
22}
23
24//output
252
263
274
285
296
307

In JavaScript, the Array object is the most iterative iterable in nature. Still, any object does possess the nature of a group of the elements—expressing the nature of a range like an integer between 0 and Infinity, can be turned into an iterable. And the scope of this article would be to help you understand and implement custom iterables.

Iterator and Iterable in JavaScript

Iteration on any array of data involves the use of the traditional for loop to iterate over its elements as below:

1let items = [1, 2, 3];
2
3for (let i = 0; i < items.length; i++) {
4 console.log(items[i]);
5}
6
7//output
8'1'
9'2'
10'3'

The above code construct works fine but poses complexity when you nest loops inside loops. This complexity will result from trying to keep track of the multiple variables involved in the loops.

To avoid the mistakes brought on by remembering loop indexes and reduce the loop’s complexity, ECMAScript 2015 developed the for...of loop construct.

This gives birth to cleaner code, but most importantly, the for...of loop provides the capacity to iterate/loop over not just an array but any iterable object.

An iterator is any object which implements the next() method that returns an object with two possible key-value pairs:

1{ value: any, done: boolean }

Using the earlier discussion on the Symbol.iterator(), we know how to implement the next() method that accepts no argument and returns an object which conforms to the above key-value pairs.

With this in mind, we implement a custom iteration process for a custom object type and successfully use the for…of loop to carry out iteration on the type. The following code block will attempt to create a LeapYear object that returns a list of leap years in the range of ( start, end) with an interval between subsequent leap years.

1class LeapYear {
2 constructor(start = 2020, end = 2040, interval = 4) {
3 this.start = start;
4 this.end = end;
5 this.interval = interval;
6 }
7
8 [Symbol.iterator]() {
9 let nextLeapYear = this.start;
10 return {
11 next: () => {
12 if (nextLeapYear <= this.end) {
13 let result = { value: nextLeapYear, done: false };
14 nextLeapYear += this.interval;
15 return result;
16 }
17 return { value: undefined, done: true };
18 },
19 };
20 }
21}

In the above code, we implemented the Symbol.iterator() method for the custom type LeapYear. We have the starting and ending points of our iteration in the this.start and this.end fields, respectively. Using the this.interval, we keep track of the interval between the first element and the next element of our iteration.

Now, we can call the for…of loop on our custom type and see its behavior and output values like a default array type.

1let leapYears = new LeapYear();
2
3for (const leapYear of leapYears) {
4 console.log(leapYear);
5}
6
7// output
82020
92024
102028
112032
122036
132040

As stated earlier, Iterable's are JavaScript structures with the Symbol.iterator()method, likeArray, String, Set. And as a result, our above LeapYear type is an Iterabletoo. This is a basic idea ofIterablesandIterators`; for more reading, refer here.

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free.

Generators in Javascript

A generator is a function that can produce many output values, and may be paused and resumed. In JavaScript, a generator is like a traditional function that produces an iterable Generator object. This behavior is opposed to traditional JavaScript functions, which execute fully and return a single value with a return statement. The Generator uses the new keyword, yield, to pause and return a value from a generator function. For more reading, refer here.

Below is the basic syntax for the declaration of a Generator:

1function* generator() {} // Object [Generator] {}

Let’s explore how generators and yield work.

1function* generate() {
2 console.log("invoked first time");
3 yield "first";
4 console.log("invoked second time");
5 yield "second";
6}
7
8let gen = generate();
9let next_value = gen.next();
10console.log(next_value);
11
12// output
13// <- invoked first time
14// <- {value: 'first', done: false}
15
16next_value = gen.next();
17console.log(next_value);
18
19// output
20// <- invoked second time
21// <- {value: 'second', done: false}

The Generator function yields an object similar to the Symbol.iterator two properties: done and value fields. In the context of our discussion, this provides that the Generator type is an Iterable. This means we can use the for…of loop on it to iterate through its returned values. The for…of loop enables us to return the value inside the value field without the need to return the done field as the for.of loop keeps track of the iteration. The for.of loop is a sugar syntax abstracting the implementation used in the previous code block.

1function* generate() {
2 console.log("invoked first time");
3 yield "first";
4 console.log("invoked second time");
5 yield "second";
6}
7
8let gen = generate();
9
10for (let value of gen) {
11 console.log(value);
12}
13
14// output
15//invoked first time
16//first
17//invoked second time
18//second

Alternatively, we can also use the concept of Generator with our LeapYear type to implement iteration on it. See below code block for the updated code snippet:

1class LeapYear {
2 constructor(start = 2020, end = 2040, interval = 4) {
3 this.start = start;
4 this.end = end;
5 this.interval = interval;
6 }
7 *[Symbol.iterator]() {
8 for (let index = this.start; index <= this.end; index += this.interval) {
9 yield index;
10 }
11 }
12 }

The above refactored and succinct code will produce the same result as earlier:

1// output
22020
32024
42028
52032
62036
72040

From the above output, using the Symbol.iterator method is much simpler than using the Generator concept. The above code snippets were used to implement a LeapYear iterator to generate leap years from the year 2020 to the year 2040.

Generator vs. Async-await — AsyncGenerator

It is possible to simulate the asynchronous behavior of code that “waits,” a pending execution, or code that appears to be synchronous even if it is asynchronous, using both the generator/yield concepts to imitate the async/await functions. A generator function’s iterator (the next method) executes each yield-expression one at a time instead of async-await, which executes each await sequentially. For async/await functions, the return value is always a promise that will either resolve to an any value or throws an error. In contrast, the return value of the generator is always {value: X, done: Boolean}, and this could make one conclude that one of these functions is built off the other. Understanding that an async function may be broken down into a generator and a promise implementation is helpful. Tada!

Now, combining generator with async/await gives birth to a new type, AsyncGenerator. In contrast to a conventional generator, an async generator’s next() method returns a Promise. You use the for await...of construct to iterate over an async generator.

The below code snippet would attempt to asynchronously fetch external data when requested and yield the value.

1let user = {
2 request: 0,
3 trials: 12,
4};
5
6async function* fetchProductButton() {
7 if (user.trials == user.request) {
8 return new Error("Exceeded trials");
9 }
10 let res = await fetch(`https://dummyjson.com/products/${user.request + 1}`);
11 let data = await res.json();
12 yield data;
13 user.request++;
14}
15
16const btn = fetchProductButton();
17
18(async () => {
19 let product = await btn.next();
20 console.log(product);
21 // OR
22 for await (let product of btn) {
23 console.log(product);
24 }
25})();

The above code snippet will return the below JSON data:

1//output
2{
3 value: {
4 id: 1,
5 title: 'iPhone 9',
6 description: 'An apple mobile which is nothing like apple',
7 price: 549,
8 discountPercentage: 12.96,
9 rating: 4.69,
10 stock: 94,
11 brand: 'Apple',
12 category: 'smartphones',
13 thumbnail: 'https://dummyjson.com/image/i/products/1/thumbnail.jpg',
14 images: [
15 'https://dummyjson.com/image/i/products/1/1.jpg',
16 'https://dummyjson.com/image/i/products/1/2.jpg',
17 'https://dummyjson.com/image/i/products/1/3.jpg',
18 'https://dummyjson.com/image/i/products/1/4.jpg',
19 'https://dummyjson.com/image/i/products/1/thumbnail.jpg'
20 ]
21 },
22 done: false
23}

The above code snippet would be a real-life example of simulating session access to always get a value as long as your session access isn’t exhausted. Using the async generator provides flexibility as it could help make paginated requests to an external API or help decouple business logic from the progress reporting framework. Also, using a Mongoose cursor to iterate through all documents while updating the command line or a Websocket with your progress.

Built-in APIs accepting iterables

A wide variety of APIs supports iterables. Examples include the Map, WeakMap, Set, and WeakSet objects. Check out this MDN document on JavaScript APIs that accepts iterables

Conclusion

In this article, you have learned about the JavaScript iterator and how to construct custom iteration logic using iteration protocols. Also, we learned that Generator is a function/object type that yields the kind of object value as an iterator. Although they are rarely utilized, they are a powerful, flexible feature of JavaScript, capable of dealing with infinite data streams, which can be used to build infinite scrolls on the frontend of a web application, to work on sound wave data, and more. They can maintain state, offering an effective technique to create iterators. Generators may imitate the async/await capabilities when combined with Promises, which enables us to deal with asynchronous code in a more direct and readable way.

A TIP FROM THE EDITOR: For more on internal details of JavaScript, check out our JavaScript Types and Values, explained and Explaining JavaScript’s Execution Context and Stack articles.

newsletter

More articles from OpenReplay Blog

Forever Functional: Sorting recipes for JavaScript

Ways of easily achieving several different sorting tasks

August 8th, 2022 · 5 min read

11 Authentication Mistakes and how to fix them

Fixes to mistakes that may imperil your website

August 5th, 2022 · 7 min read
© 2022 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552