Since 2015, EcmaScript6 (ES6) has brought many advancements in JavaScript coding practices. Numerous modern concepts were introduced to JavaScript, greatly improving the coding experience. In this article, you'll learn about iterators and generators in JavaScript.

Iterators and generators are two different concepts, but they're used in similar ways. They're used to iterate through arrays and objects in JavaScript.

Iterators

Iterators are like advanced loops that can be paused. Iterators consist of the next() function, which returns the value and the done status. The value field is the value in the array at a given index. done is the boolean value that returns the status of completion for the iteration through the loop.

Here's an example that demonstrates how 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);
console.log(fruits.next().value);

Output:

Mango

When you pass the fruitsArray array in the fruitIter() method, it returns an iterator that's stored in the fruits variable. The index variable in the fruitIter() method gets initialized to 0. This method returns the next() function that helps in looping through the array. The next() function checks whether the index is less than fruitsArray length. If so, it returns two variables: the fruit name at that index, and the done status. While returning these values, it also increments the index value.

To check how this method works and print the fruit name, you need to call the next() function on the fruits iterator and get access to its value.

Related: What Is a Function in Programming?

Generators

Generators are similar to Iterators but they return multiple values. These values are called yield values. Generator functions are written using the function* syntax. * denotes that it's not a normal function, but a generator. Here's an example of generators:

        function* printFruits(){

 yield "Mango";
 yield "Banana";
 yield "Grapes";
}

const fruit = printFruits();
console.log(fruit.next());

Output:

{value: 'Mango', done: false}

In this example, yield is the iterator. When you call the function printFruits(), and print fruit.next(), it gives you an object where you get the value. The done status denotes whether all values have been iterated through.

Learn Data Structures Using ES6 Classes in JavaScript

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