Published on
10 min read

JavaScript generators and iterators

Authors
  • avatar
    Name
    John Moscarillo
    Twitter

JavaScript generators and iterators are powerful features that allow developers to control the flow of code execution in a more flexible and efficient manner. Here's an overview of both:

Iterators

An iterator is an object that provides a sequence of values, typically by iterating over an iterable object. An iterable object is any object that has a Symbol.iterator method that returns an iterator object. The most common iterables in JavaScript are arrays, strings, and maps. An iterator object has a next() method, which returns an object with two properties: value (the next value in the sequence) and done (a boolean indicating whether the iterator has reached the end of the sequence).

Here's an example of iterating over an array using an iterator:

const arr = [1, 2, 3];
const iterator = arr[Symbol.iterator]();
let result = iterator.next();
while (!result.done) {
  console.log(result.value);
  result = iterator.next();
}

Generators

Generators are a type of iterator that can be paused and resumed. They are defined using a special syntax: the function* declaration. Within a generator function, you can use the yield keyword to pause execution and return a value to the caller. The caller can then resume execution of the generator at the point where it was paused.

Here's an example of a generator function that generates a sequence of Fibonacci numbers:

function* fibonacci() {
  let a = 0;
  let b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const fib = fibonacci();
console.log(fib.next().value); // 0
console.log(fib.next().value); // 1
console.log(fib.next().value); // 1
console.log(fib.next().value); // 2
console.log(fib.next().value); // 3
// and so on...

In this example, the fibonacci function returns a generator object, which can be used to generate an infinite sequence of Fibonacci numbers. The yield keyword is used to return the current value in the sequence, and the caller can use the next() method to retrieve the next value. The generator function continues to execute until it encounters a yield statement, at which point it is paused and waits for the next next() method call to resume execution.