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())

You can also try this code with Online Javascript Compiler
Run Code
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())

You can also try this code with Online Javascript Compiler
Run Code
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());

You can also try this code with Online Javascript Compiler
Run Code
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}`);
}

You can also try this code with Online Javascript Compiler
Run Code
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!