javascript

Iterators and Generators


Iterators and generators are powerful features introduced in JavaScript to facilitate the iteration over data structures such as arrays, objects, or custom data structures.

 

Iterators:

An iterator is an object that provides a way to access elements sequentially from a collection of data. It follows the Iterator protocol, which consists of a next() method that returns an object with two properties: value, which represents the current value, and done, which indicates whether the iteration has finished.

 

Example:
 

// Creating an iterator for an array
let array = [1, 2, 3];
let iterator = array[Symbol.iterator]();

// Iterating over the array using the iterator
console.log(iterator.next()); // Output: { value: 1, done: false }
console.log(iterator.next()); // Output: { value: 2, done: false }
console.log(iterator.next()); // Output: { value: 3, done: false }
console.log(iterator.next()); // Output: { value: undefined, done: true }

 

Generators:

Generators provide a more convenient way to create iterators in JavaScript. They are functions that can be paused and resumed, allowing you to generate a sequence of values lazily. Generators are defined using the “function*” syntax and yield values using the yield keyword.

 

Example:

// Generators
// Generates letters of the alphabet.
function* alphabet() {
    for (let charCode = 65; charCode <= 90; charCode++) {
        yield String.fromCharCode(charCode);
    }
}

// Using the generator to print the letters of the alphabet
for (let letter of alphabet()) {
    console.log(letter);
}