Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Iterator
3.
Making an object iterable or implementing an iterator function
4.
Generator
5.
Implementing generator function
6.
Usecases of generator
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Explain Iterators and generators

Author Malay Gain
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

With the introduction of ES6, iterators, and generators have officially been added to javascript that bring the concept of iteration directly into the core language by providing a mechanism for customizing the behavior of for…of  loops. In this article first, we will know what iterator is, how it works, and the implementation of its interior function. Then we will discuss the generator and its functionality.

 

Iterator

Iterator is an object that defines the sequence of an iterable data structure (such as array, map, string). Any object that implements the iterable protocol can be iterated by using iterator. It is done by a method whose key is Symbol.iterator

 

Any object can be made iterable by implementing the iterator function.

 

Iterator uses next( ) method to access next element in the iterable data structure .

 

Let’s see the below example for better understanding

var arr=[1,2,3]

const itr= arr[Symbol.iterator]()  //creating iterator for traversing the array

//using next() method to access next element in the array
console.log(itr.next());
console.log(itr.next());
console.log(itr.next());
console.log(itr.next());

Output

{ value: 1, done: false }
{ value: 2, done: false }
{ value: 3, done: false }
{ value: undefined, done: true }

 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Making an object iterable or implementing an iterator function

It is easy to traverse over a simple object by using predefined next method. But for complex objects whose values are also an object, we cann’t easily iterate over the object. For example,

const contest={
     Problem1:['Utkarsh','Striver','Priyansh','Anish'],
     Problem2:['Utkarsh','Striver','Priyansh'],
     Problem3:['Utkarsh','Striver','Priyansh'],
     Problem4:['Utkarsh','Striver'],
 }
 
 const itr=contest[Symbol.iterator]()
 console.log(itr.next())

 

This throws an error as we cann’t directly use interator for this complex object. To make this object iterable, we first need to define interator function by accessing through Symbol.iterator.

const contest={
     team1:['Utkarsh','Striver'],
     team2:[,'Priyansh','Anish'],
     team3:['Anirban','Souvik'],
     team4:['Arnab','Rahul'],
 }

 //defining iterator function
 
 contest[Symbol.iterator]=function()
 {
   const teams = Object.keys(this);
  let teamId = 0;
  let participantIdx = 0;

  return {
    next: () => {
      //  already iterated over all the teams
      if (teamId > teams.length - 1) {
        return {
          value: undefined,
          done: true,
        };
      }

      const participants = this[teams[teamId]];
      const participant = participants[participantIdx];

      const isLastParticipant = participantIdx >= participants.length - 1;

      participantIdx++;
      if (isLastParticipant) {
        // Resetting  Participant index
        participantIdx = 0;
        // Jump to next team
        teamId++
      }

      return {
        value: participant, 
        done: false
               
      };
    },
  };
 }
 
 
 const itr= contest[Symbol.iterator]();
 
 //getting all participants of the contest
 console.log(itr.next())
 console.log(itr.next())
 console.log(itr.next())
 console.log(itr.next())
 console.log(itr.next())
 console.log(itr.next())
 console.log(itr.next())
 console.log(itr.next())
  console.log(itr.next())

Output

{ value: 'Utkarsh', done: false }
{ value: 'Striver', done: false }
{ value: 'Priyansh', done: false }
{ value: 'Anish', done: false }
{ value: 'Anirban', done: false }
{ value: 'Souvik', done: false }
{ value: 'Arnab', done: false }
{ value: 'Rahul', done: false }
{ value: undefined, done: true }

Generator

Generators are one kind tool that can be used to create iterables. 

 

In another way, it can be assumed as processes that can pause and resume while executing that particular code. 

 

Generators allows us to define iterative algorithm by writing a single function whose execution is not continuous. 

 

Implementing generator function

Defining iterator functions is difficult and error-prone whereas generator functions are less error-prone and allow us to create iterators more efficiently.

 

function*  keyword is used to define the generator function. The  yield keyword is used to know which part of the function, the iterator should iterate. Actually here yield acts as an operator with which the generator can pause itself. 

 

Let’s see an example of a generator function below.

//generator function

function* generator(i) {
    yield i + 1;
    yield i + 2;
}

var itr = generator(5);

//iterating over various parts of the function
console.log(itr.next()); 
console.log(itr.next());
console.log(itr.next());

 

 

Output

{ value: 6, done: false }
{ value: 7, done: false }
{ value: undefined, done: true }

Usecases of generator

The main use-case of generators is, it can be used to create iterables for complex objects by defining generator function. It mainly uses pause and resume execution characteristics of the generator function.

 

Let’s understand this concept through an example.

function* objectEntries(obj) {
    const keys = Object.keys(obj);

    for (const key of keys) {
        yield [key, obj[key]];
    }
}

const customers = { customer1: 'Sohini', customer2: 'Riya' };

for (const [key,value] of objectEntries(customers)) {
    console.log(`${key}: ${value}`);
}

 

 

Output

customer1: Sohini
customer2: Riya

 

 

In the above code snippet,

objectEntries returns iterable of customers object . for..of loop uses this iterable to retrieve the next yield as key-value pair.

FAQs

1. What are Iterators in JS?

An Iterator is an object that defines the sequence of an iterable data structure (such as array, map, string). Any object that implements the iterable protocol can be iterated by using iterator. An Iterator uses the ‘next( )’ method to access the next element in the iterable data structure.

2. What are Generators in JS?

A Generator is one of a kind of tool that can be used to create iterables i.e. it can be assumed as processes that can pause and resume while executing that particular code. Generators allow one to define iterative algorithms by writing a single function whose execution is not continuous. 

 

Key Takeaways

This article covered iterators and generators in javascript.

Recommended Readings:

Check out the Coding Ninjas Studio library for getting a better hold of the data structures and algorithms and the guided path for learning javascript from basics.

 

Side by side, you can also practice a wide variety of coding questions commonly asked in interviews in Coding Ninjas Studio. Along with coding questions, you can also find the interview experience of scholars working in renowned product-based companies here. 

 

Happy learning!

Previous article
What are Differences Between Cookie, Local Storage, and Session Storage
Next article
What object.freeze() does, How to make objects immutable?
Live masterclass