An introduction to iterators and generators in JavaScript


Since 2015, EcmaScript6 (ES6) has brought many advancements in JavaScript coding practices. Many modern concepts have been introduced into JavaScript, greatly improving the coding experience. In this article, you will learn about iterators and generators in JavaScript.

Iterators and generators are two different concepts, but they are used in a similar way. They are used to browse arrays and objects in JavaScript.


Iterators are like advanced loops that can be paused. The iterators are made up of Following() function, which returns the value and the completed state. The value field is the value in the array at a given index. ended is the Boolean value that returns the completion status of the iteration in the loop.

Here is an example that shows how the iterators:

function fruitIter(fruits){
let index = 0;
return {
next: function(){
return index < fruits.length ? { value: fruits[index++], done: false } : {done: true}
const fruitsArray = ["Mango", "Banana", "Grapes"];
const fruits = fruitIter(fruitsArray);

Go out:


When you pass the fruit table table in the fruitIter () method, it returns an iterator which is stored in the fruits variable. The index variable in the fruitIter () The method is initialized to 0. This method returns the Following() function that helps to loop through the array. The Following() the function checks if the index is less than fruit table length. If so, it returns two variables: the name of the fruit at this index and the ended status. When returning these values, it also increments the value of the index.

To check the operation of this method and print the name of the fruit, you must call the Following() function on the fruits iterator and access its value.

Related: What is a Function in Programming?


Generators are similar to iterators, but they return multiple values. These values ​​are called efficiency values. Generating functions are written using the function * syntax. * indicates that this is not a normal function, but a generator. Here is an example of generators:

function* printFruits(){
yield "Mango";
yield "Banana";
yield "Grapes";
const fruit = printFruits();

Go out:

{value: 'Mango', done: false}

In this example, yield is the iterator. When you call the function printFruits (), and print (), this gives you an item that you get the value of. The ended status indicates whether all values ​​have been iterated.

Learn Data Structures Using ES6 Classes in JavaScript

JavaScript ES6 has brought a lot of advancement in coding practices. Not least is building data structures using ES6 classes. To push. pop, and stack your way to the top and become a JavaScript pro!

A cardboard box

How to create data structures with JavaScript ES6 classes

With the introduction of JavaScript ES6, custom data structures appeared. Here’s how to create and apply them.

Read more

About the Author

Leave A Reply

Your email address will not be published.