Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 9

Iterables vs. Iterators

This lesson is built with resources from youtube.com, developer.mozilla.org and 1 more site.

Hello! Welcome to the second module of our course. In the previous module, we explored how Symbols, particularly well-known symbols, act as hooks to customize JavaScript's core behavior. We ended with Symbol.match, which allows any object to define its own logic for String.prototype.match().

Today, we begin our journey into one of the most fundamental concepts in modern JavaScript: iteration. This entire system is built upon another well-known symbol, Symbol.iterator, and relies on a clear separation of concerns. Your learning outcome for this lesson is to: Distinguish between the iterable and iterator protocols.

To achieve this, we will:

  • Explore the motivation behind creating a standardized iteration system in JavaScript.
  • Formally define the iterator protocol: the "worker" that produces values.
  • Formally define the iterable protocol: the "data source" that provides an iterator.
  • Visualize how these two protocols collaborate to enable constructs like the for...of loop.

This lesson lays the conceptual foundation for the entire module. Mastering the distinction between what is iterable and what is an iterator is crucial for understanding and creating custom data structures, generators, and advanced asynchronous patterns.

1. The Need for a Uniform Iteration Model

Before ES2015, iterating over different types of collections was inconsistent. You might use a for loop with an index for an array, a for...in loop for object keys (which has its own pitfalls), or other bespoke methods for collections like NodeList in the browser. There was no single, unified way to say "give me the next item until you're done."

The introduction of iteration protocols solved this by creating a standard "language" for iteration that any data structure can implement. This brings a powerful form of polymorphism to JavaScript, similar to how implementing an Iterable interface in Java or Python allows an object to be used in a for-each loop.

To understand this context better, please watch the beginning of the following video.

Advanced JavaScript Crash Course

This segment from a 'Codevolution' video provides excellent historical context, explaining the problems with pre-ES2015 iteration and motivating the introduction of the iterable and iterator protocols.

Watch from the beginning of the 'Iterables and Iterators' section until the formal definitions are introduced. Focus on the two main difficulties of the old iteration style that are highlighted.

As the video explains, the new protocols abstract away the complexity of how to access elements, allowing us to focus on what to do with them, all while using a consistent syntax like the for...of loop.


2. The Two Protocols: A Separation of Concerns

The elegance of JavaScript's iteration system lies in its separation of two distinct responsibilities, defined by two protocols.

The Iterator Protocol: The "Worker"

An iterator is an object designed to do one thing: produce a sequence of values, one at a time. It's like a cursor or a pointer that moves through a collection.

To be considered an iterator, an object must adhere to the iterator protocol.

The Contract: An object is an iterator if it has a next() method.

  • This next() method takes no arguments.
  • It returns an object with two properties:
    • value: The current value in the sequence.
    • done: A boolean that is false if there are more values to come, and true when the iteration is complete.

Let's see the simplest possible iterator in action.

Iterator, Iterable and IterableIterator // Professional JavaScript MasterClass

The video 'Iterator, Iterable and IterableIterator' by Basarat starts with a perfect, hands-on demonstration of creating a manual iterator. This makes the abstract definition very concrete.

Watch the first two minutes of this video. The author builds a range function that returns a simple iterator object, clearly showing the structure of the next() method and the { value, done } result.

Notice that the iterator itself is stateful. In the video's example, the value variable is enclosed within the scope of the range function, and the next method updates it on each call.

The Iterable Protocol: The "Data Source"

An iterable is an object that represents a data source or collection and signals that it can be iterated over. It doesn't perform the iteration itself; instead, its job is to provide an iterator on demand.

To be considered iterable, an object must adhere to the iterable protocol.

The Contract: An object is iterable if it has a method keyed by Symbol.iterator.

  • This [Symbol.iterator]() method is a "factory" for iterators.
  • When called, it must return a new, fresh iterator object that conforms to the iterator protocol described above.

Many of JavaScript's built-in types, like Array, String, Map, and Set, are built-in iterables. This is why you can use them directly in a for...of loop.

Iterator, Iterable and IterableIterator // Professional JavaScript MasterClass

Continuing with the same video, the author now explains the iterable protocol and demonstrates how built-in types like arrays and strings conform to it.

Watch the next segment of the video. Pay close attention to how Symbol.iterator is used to get an iterator from an array, and how that iterator is then consumed manually with .next().


3. How They Work Together

The key to understanding this system is seeing how the two protocols collaborate. When a JavaScript construct like a for...of loop or the spread operator (...) encounters an iterable object, a two-step process unfolds:

  1. Get the Iterator: It calls the object's [Symbol.iterator]() method. This asks the iterable data source to "manufacture" and return a worker (an iterator) that knows how to traverse its data.
  2. Consume the Iterator: It then repeatedly calls the next() method on the returned iterator object. It continues to process the value from each result until the done property comes back as true.

This relationship is depicted beautifully in the following diagram.

Iterable and Iterator Protocol Relationship Diagram
This diagram illustrates the core relationship: An **Iterable** object acts as a factory that, when requested, **creates** an **Iterator** object. The `for...of` loop is the consumer that initiates this process and then uses the resulting iterator.

This "factory" design is critical. Because [Symbol.iterator]() is a method that returns a new iterator each time, you can iterate over the same data source multiple times, even concurrently, without the iterators interfering with each other.

For a deeper dive into the "why" behind this design, the following resource is excellent.

JavaScript iterables and iterators - JS Rocks

The article 'JavaScript iterables and iterators' from JS Rocks has a fantastic Q&A section that explains the design rationale behind the protocols.

Read the section titled 'Is all this complexity necessary?'. Focus on the first two questions: 'Why is [Symbol.iterator] a method that returns an iterator?' and 'Why iterators' next method returns a data structure?'. This will solidify your understanding of the design choices.


4. Distinguishing in Practice: A Summary

Let's consolidate the distinction into a clear table.

Feature Iterable Protocol Iterator Protocol
Role A data source or collection. A "pointer" or "cursor" that traverses the data.
Contract Must implement the [Symbol.iterator]() method. Must implement the next() method.
Return Value The [Symbol.iterator]() method returns a new iterator. The next() method returns an object: { value: any, done: boolean }.
State Generally stateless regarding iteration. Stateful; it tracks the current position in the sequence.
Consumer Consumed by for...of, spread syntax (...), Array.from(). Directly consumed by code that repeatedly calls .next().
Analogy A playlist (the collection of songs). The "play" button that goes to the next song.

Test your understanding!

Consider the two objects below, counter and range. One is an iterator, and one is an iterable.

// Object 1
const counter = {
  count: 0,
  next: function() {
    if (this.count < 3) {
      return { value: this.count++, done: false };
    }
    return { value: undefined, done: true };
  }
};

// Object 2
const range = {
  from: 1,
  to: 3,
  [Symbol.iterator]: function() {
    let current = this.from;
    const last = this.to;
    
    // This returned object is the iterator
    return {
      next: () => {
        if (current <= last) {
          return { value: current++, done: false };
        } else {
          return { value: undefined, done: true };
        }
      }
    };
  }
};
  1. Which object is the iterator and which is the iterable? Explain your reasoning based on the protocols.
  2. Which object can you use directly in a for...of loop (e.g., for (const num of object))? Why?
  3. How would you have to change the counter object to make it work with for...of?
Show answer
  1. counter is an iterator. It conforms to the iterator protocol because it has a next() method that returns an object with value and done properties. range is an iterable. It conforms to the iterable protocol because it has a method keyed by [Symbol.iterator] that returns an iterator object.

  2. You can use range directly in a for...of loop. The loop requires an iterable. It will call range[Symbol.iterator]() to get the iterator and then use that to loop. It cannot use counter directly because counter does not have a [Symbol.iterator]() method.

  3. To make counter work with for...of, you would need to make it iterable. The simplest way is to add a [Symbol.iterator] method that returns the object itself, since it's already an iterator. This makes it an iterable iterator.

    const counter = {
      count: 0,
      next: function() {
        if (this.count < 3) {
          return { value: this.count++, done: false };
        }
        return { value: undefined, done: true };
      },
      // Make it iterable
      [Symbol.iterator]: function() {
        return this;
      }
    };
    
    for (const c of counter) {
        console.log(c); // 0, 1, 2
    }
    
    // Note: This makes the iterator consumable only once!
    // After the first loop, counter.count will be 3.
    // A second `for...of` loop over `counter` would produce nothing.
    // This highlights why iterables usually return a *new* iterator each time.
    


Conclusion

In this lesson, we have carefully dissected the two protocols that govern iteration in JavaScript.

Key Takeaways:

  • Iterable Protocol: An object is iterable if it implements a [Symbol.iterator] method. This method's purpose is to act as a factory, producing a fresh iterator.
  • Iterator Protocol: An object is an iterator if it implements a next() method. This method is called repeatedly to produce a sequence of values, each wrapped in a { value, done } object.
  • The two protocols work in tandem: consumers like for...of request an iterator from an iterable, and then use that iterator to walk through the sequence of values.
  • This separation of concerns allows for a flexible and powerful system where any object can define its own iteration behavior while plugging into standard language features.

Next Up

You now understand the "what" and "why" of JavaScript's iteration protocols. In our next lesson, we will move from theory to practice. You will apply this knowledge to implement the iterator protocol manually on a custom object using Symbol.iterator, building your own iterable object from the ground up.