A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/difference-between-generators-and-iterators-in-javascript/ below:

Difference between Generators and Iterators in JavaScript

Difference between Generators and Iterators in JavaScript

Last Updated : 11 Dec, 2023

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.

JavaScript
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);
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.

JavaScript
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:

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4