JavaScript Generators

Manish Kumar
4 min readJan 12, 2023

Welcome to our lesson on JavaScript Generators. In this lesson, we will learn what JavaScript Generators are and how they can be used to write more efficient and expressive code.

Lets begin with more familiar term, JavaScript Iterators:

JavaScript iterators are objects that allow developers to traverse and manipulate the elements of a data structure, such as an array or a string. An iterator object defines a next() method which returns the next item in the sequence, and a done property which indicates whether the end of the sequence has been reached.

The built-in Array and String types in JavaScript have a default iterator that can be accessed using the Symbol.iterator property. Developers can also create custom iterator objects by implementing the iterator protocol, which consists of a next() method that returns an object with two properties: value and done.

In addition to for...of loops, the spread operator and the Array.from() method can also be used with iterators.

Iterators are commonly used with the for...of loop to loop through the elements of an array or a string.

let arr = [1, 2, 3];
for (let element of arr) {
console.log(element);
}

This code will log the numbers 1, 2 and 3 to the console.

Introduction to JavaScript Generators

JavaScript generators are a special type of iterator that allow developers to control the flow of iteration. A generator function is defined using the function* syntax and can be used to create an iterator object.

The generator function uses the yield keyword to pause execution and return a value from the iterator. Each time the generator's next() method is called, the function resumes execution from where it last paused, until it encounters another yield statement or the end of the function.

Generators can be used to create complex data structures, such as infinite sequences, and to implement the iterator pattern more efficiently.

function* generatorFunc() {
yield 1;
yield 2;
yield 3;
}
let iterator = generatorFunc();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

The generator function generatorFunc, when called, returns an iterator object. Each time the next() method is called on the iterator, the generator function runs until it encounters the next yield statement and returns the value. The done property of the returned object is false until the generator function returns.

Generators can also take arguments and use local variables, and they can be used with the for...of loop as well as with other array methods such as spread and Array.from().

Q) How Generators are different from Iterators?

Generators and iterators are both used to traverse and manipulate the elements of a data structure in JavaScript, but they have some key differences.

  • Function: An iterator is an object that implements a next() method and has a done property, while a generator is a special type of function that uses the function* syntax and the yield keyword to create an iterator.
  • Execution Control: Iterators simply return the next value in a sequence, while generators allow developers to control the flow of execution using the yield keyword. With generators, the developer can pause the function execution, return a value, and then resume execution later.
  • Memory Management: Iterators load all the data in memory at once and then iterate through it, whereas generators only load the data as needed and discard it after use, which can help with memory management for large data sets.
  • Usage: Iterators are commonly used with the for...of loop to loop through the elements of an array or a string, while generators can be used to create complex data structures, such as infinite sequences, and to implement the iterator pattern more efficiently.
  • Returning values: Iterator’s next() method returns an object that contains a value and a done property, whereas generator's next() method returns an object that contains a value property, and a done property. And generators have an additional return() method which allows the generator to return a final value and set the done property to true.

Overall, both Iterators and Generators are useful for working with data structures in JavaScript, but generators offer more flexibility and control over the iteration process, making them suitable for more complex use cases.

Creating a Generator:

A generator in JavaScript is created using the function* syntax, which is followed by the generator function name. Within the function, the yield keyword is used to pause the execution and return a value. Here is an example of a simple generator function that returns the numbers from 1 to 3:

function* numbersGenerator() {
yield 1;
yield 2;
yield 3;
}

To use this generator function, you would create an iterator object by calling the function and then repeatedly call the next() method on the iterator to get the next value from the generator.

let iterator = numbersGenerator();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

Each time the next() method is called, the generator function runs until it encounters the next yield statement and returns the value. The done property of the returned object is false until the generator function returns.

You can also use the generator function with a for-of loop, which will automatically call the next() method and assign the value to a variable for each iteration

for (let num of numbersGenerator()) {
console.log(num);
}

This will log the numbers 1, 2 and 3 to the console.

Generators can also take arguments and use local variables to make them more flexible, and they can be used with other array methods such as spread and Array.from().

Generator use cases

  • Iterating over large data sets
  • Implementing lazy evaluation
  • Creating infinite sequences

Happy Coding!!!

--

--