JavaScript — How to Implement an Iterator

In the previous Future Studio tutorial, we looked into the details of what’s Symbol.iterator in JavaScript. Symbol.iterator is a global constant for the @@iterator property used by JavaScript’s iteration protocol. When looping through an iterable, for example, an array, JavaScript looks for the @@iterator property that returns a function providing the iterator.

This tutorial shows you how to implement an iterator in JavaScript.

Node.js Series Overview

  1. String Replace All Appearances
  2. Remove All Whitespace From a String in JavaScript
  3. Generate a Random ID or String in Node.js or JavaScript
  4. Remove Extra Spaces From a String in JavaScript or Node.js
  5. Remove Numbers From a String in JavaScript or Node.js
  6. Get the Part Before a Character in a String in JavaScript or Node.js
  7. Get the Part After a Character in a String in JavaScript or Node.js
  8. How to Check if a Value is a String in JavaScript or Node.js
  9. Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
  10. Check if a Value is a String in JavaScript and Node.js
  11. Limit and Truncate a String to a Given Length in JavaScript and Node.js
  12. Split a String into a List of Characters in JavaScript and Node.js
  13. How to Generage a UUID in Node.js
  14. Reverse a String in JavaScript or Node.js
  15. Split a String into a List of Lines in JavaScript or Node.js
  16. Split a String into a List of Words in JavaScript or Node.js
  17. Detect if a String is in camelCase Format in Javascript or Node.js
  18. Check If a String Is in Lowercase in JavaScript or Node.js
  19. Check If a String is in Uppercase in JavaScript or Node.js
  20. Get the Part After First Occurrence in a String in JavaScript or Node.js
  21. Get the Part Before First Occurrence in a String in JavaScript or Node.js
  22. Get the Part Before Last Occurrence in a String in JavaScript or Node.js
  23. Get the Part After Last Occurrence in a String in JavaScript or Node.js
  24. How to Count Words in a File
  25. How to Shuffle the Characters of a String in JavaScript or Node.js
  26. Append Characters or Words to a String in JavaScript or Node.js
  27. Check if a String is Empty in JavaScript or Node.js
  28. Ensure a String Ends with a Given Character in JavaScript or Node.js
  29. Left-Trim Characters Off a String in JavaScript or Node.js
  30. Right-Trim Characters Off a String in JavaScript or Node.js
  31. Lowercase the First Character of a String in JavaScript or Node.js
  32. Uppercase the First Character of a String in JavaScript or Node.js
  33. Prepend Characters or Words to a String in JavaScript or Node.js
  34. Check if a String is a Number
  35. Convert a String to Buffer
  36. Prevent Line Breaks in String Template Literals
  37. How to Implement a Custom `toString` Method
  38. What Is `Symbol.toStringTag` and How to Use It (Coming soon)

Implement an Iterator in JavaScript

The JavaScript language has a specification for iteration protocols. This specification contains two protocols: the iterable protocol and the iterator protocol. We’re interested in the iterator protocol that defines a way of providing a sequence of values.

You may implement an iterator yourself following the iterator protocol. An iterator must implement a next() function. This next() function returns an object containing two properties: done and value.

The done property is a boolean and value contains the next value in the sequence. The value property is optional which happens when your sequence ends and the last value is returned. In such cases, you’re returning { done: true, value: undefined }.

Here’s an implementation of an iterator class that wraps a JavaScript array:

class MyIterator {  
  /**
   * Create a new iterator instance for the given `values`.
   *
   * @param {any[]} values
   */
  constructor (values) {
    this.values = values
    this.pointer = 0
  }

  /**
   * Returns the next iteration result following the JS iteration protocol. The
   * iteration object contains the next item if there’s one available and a
   * boolean `done` attribute telling JS whether all items are iterated.
   */
  next () {
    return this.pointer < this.values.length
      ? { done: false, value: this.values[this.pointer++] }
      : { done: true, value: undefined }
  }
}

You can now use the MyIterator class in your objects. For example, use the Symbol.iterator and create a function that returns an instance of MyIterator. Here’s a sample implementation for it:

const iterator = {  
  [Symbol.iterator]() {
    return new MyIterator([1, 2, 3, 4])
  }
}
console.log([...iterator])  
// [1, 2, 3, 4]

The sample console log line shows that the iterator is working.

Make the Iterator Iterable

In some situations you also want your iterator to be iterable. That means the iterator must implement a method identified using Symbol.iterator. You can extend the MyIterator class from above by implementing a function for the Symbol.iterator and return the iterator instance itself:

class MyIterator {

  // … the code from above

  /**
   * Returns itself to allow re-using this iterator when exiting a loop early (via break, return, etc.).
   */
  [Symbol.iterator] () {
    return this
  }
}

Such an iterator is called iterable iterator.

Using a Generator Function

You can also implement an iterator using a generator function. An iterator implemented as a generator function should yield each value in the sequence. You may also delegate the value generation to another generator function.

Here’s an example of a MyArray class wrapping a JavaScript array. It implements a generator function as an iterator. Its iterator delegates the iterator to JavaScript’s native array iterator functionality:

class MyArray {  
  /**
   * Create a new array instance providing chainable operations. This instance
   * shallow clones the original values and works with the clone.
   *
   * @param {any[]} values
   *
   */
  constructor (values) {
    this.values = [].concat(values ?? [])
  }

  /**
   * Returns an iterator for the values.
   *
   * @returns {IterableIterator<T>}
   */
  * [Symbol.iterator] () {
    yield * this.values
  }
}

The MyArray class delegates the iteration using a generator function. This generator function passes the iterator down to the native array and uses its iterable.

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.