Skip to content

Iterators and generators in JavaScript

  • by

In JavaScript, iterators and generators are powerful language features that allow you to iterate over collections of data or generate sequences of values. They provide a convenient way to work with data in a controlled and efficient manner.

Iterators: An iterator is an object that implements the Iterator protocol, which consists of a next() method that returns an object with two properties: value and done. The value property represents the current value in the iteration, and the done property indicates whether the iterator has reached the end of the collection.

To create an iterator, you need to define a function or method that returns an iterator object.

function createIterator(array) {
  let index = 0;

  return {
    next: function() {
      if (index < array.length) {
        return { value: array[index++], done: false };
      } else {
        return { done: true };
      }
    }
  };
}

const myArray = [1, 2, 3];
const iterator = createIterator(myArray);

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { done: true }

Generators: Generators are a special type of iterator that simplifies the process of defining iterators. They use the function* syntax and the yield keyword to define a generator function. Generator functions allow you to create iterators by writing code that looks like a standard sequential function.

function* generateSequence() {
  yield 1;
  yield 2;
  yield 3;
}

const generator = generateSequence();

console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { done: true }

Generators provide a more concise and readable way to define iterators compared to the manual approach shown earlier.

Both iterators and generators are widely used in JavaScript to work with collections, iterate over data streams, and handle asynchronous operations. They provide a flexible and efficient way to process data and control the flow of execution.

Iterators and generators in JavaScript example

Simple example code of iterators and generators in JavaScript:

Iterator Example: Iterating over an Object

const myObject = {
  a: 1,
  b: 2,
  c: 3
};

myObject[Symbol.iterator] = function() {
  const keys = Object.keys(this);
  let index = 0;

  return {
    next: function() {
      if (index < keys.length) {
        const key = keys[index++];
        return { value: { key, value: myObject[key] }, done: false };
      } else {
        return { done: true };
      }
    }
  };
};

for (const item of myObject) {
  console.log(item);
}

Output:

Iterators and generators in JavaScript

Generator Example: Infinite Fibonacci Sequence

function* fibonacciGenerator() {
  let [prev, current] = [0, 1];

  while (true) {
    yield current;
    [prev, current] = [current, prev + current];
  }
}

const fibonacci = fibonacciGenerator();

console.log(fibonacci.next().value); // 1
console.log(fibonacci.next().value); // 1
console.log(fibonacci.next().value); // 2
console.log(fibonacci.next().value); // 3
console.log(fibonacci.next().value); // 5
// and so on...

These examples demonstrate how iterators and generators can be used in different scenarios, whether it’s iterating over an object’s properties or generating infinite sequences.

Do comment if you have any doubts or suggestions on this Js code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading