JavaScript: Iterators & Generators
Iterators
In JavaScript, an iterator is an object that provides a sequence of values, one at a time, when requested. Iterators are used to loop over iterable objects, such as arrays or strings, and provide a convenient way to access and manipulate their contents.
Here’s an example of using an iterator to loop over an array:
const array = [1, 2, 3];
for (const value of array) {
console.log(value);
}
In this example, we use a for...of
loop to iterate over the array
and log each value to the console. The for...of
loop implicitly uses the array's iterator to access each value in the sequence.
Generators
In JavaScript, generators are functions that allow you to define an iterative algorithm by writing a single function that can maintain its own state. Generators are defined using a special syntax, the function*
notation, and yield values using the yield
keyword.
Here’s an example of a generator that generates an infinite sequence of even numbers:
function* generateEvenNumbers() {
let number = 0;
while (true) {
yield number;
number += 2;
}
}
In this example, we define a generator function generateEvenNumbers
using the function*
syntax. The function initializes a variable number
to 0 and enters an infinite loop, yielding the current value of number
using the yield
keyword and then incrementing it by 2.
We can then use this generator to generate the first 10 even numbers like this:
const generator = generateEvenNumbers();
for (let i = 0; i < 10; i++) {
console.log(generator.next().value);
}
In this example, we create a new instance of the generateEvenNumbers
generator and loop over it 10 times using a for
loop. Each time through the loop, we call the next()
method on the generator to get the next value in the sequence and log it to the console using the value
property of the returned object.
Generators can be a powerful tool for defining complex iterative algorithms that would be difficult to express using traditional loops or iterators.