Open In App

Difference between Generators and Iterators in JavaScript

Generators

The Generators are a special type of function in JavaScript that can be paused and resumed during their execution. They are defined using the asterisk (*) after the function keyword. The Generators use the yield keyword to yield control back to the caller while preserving their execution context. The Generators are useful for creating iterators, asynchronous code, and handling sequences of data without loading all the data into the memory at once.

Example: In this example, we will see a simple generator function that yields values in the sequence.






function* GFG() {
    yield 10;
    yield 20;
    yield 30;
}
const generator = GFG();
console.log(generator.next().value);
console.log(generator.next().value);
console.log(generator.next().value);

Output
10
20
30

Iterators

The Iterators are objects with a special structure in JavaScript. They must have a next() method that returns an object with the value and done properties. The value property represents the next value in the sequence and the done property indicates whether there are more values to be iterated. The Iterators are commonly used for iterating over data structures like arrays, maps, and sets.



Example: In this example, we will see an iterator looping through an array.




const colors = ['red', 'green', 'blue'];
const GFG = colors[Symbol.iterator]();
console.log(GFG.next());
console.log(GFG.next());
console.log(GFG.next());
console.log(GFG.next());

Output
{ value: 'red', done: false }
{ value: 'green', done: false }
{ value: 'blue', done: false }
{ value: undefined, done: true }

Difference between Generators and Iterators:

Generators

Iterators

Functions with the asterisk (*) and yield keyword.

Object that provides a sequence of values.

Often used for asynchronous operations.

Typically used for looping through collections.

It can Pause and resume during the execution.

The Sequentially iterate through data elements.

The Explicitly define and yield data.

The Automatically iterate through existing the data structures.

Every generator is an iterator.

Every iterator is not a generator.


Article Tags :