Course contentsShow
← JavaScript
Lesson 1073 of 2,72325. Iterators and GeneratorsFree lesson

What Is the Iterator Protocol?

Understanding the contract that makes objects iterable in JavaScript.

What Is the Iterator Protocol?

You'll learn: What makes an object "iterable" in JavaScript and the contract that enables consistent iteration.

The Core Idea

The iterator protocol is JavaScript's formal agreement about how objects can be looped over. It's a simple contract: if an object provides a specific method that returns values one at a time in a predictable way, JavaScript knows how to iterate through it.

Think of it like a vending machine protocol. The machine doesn't care what snacks are inside—it just needs a standard button interface. Similarly, JavaScript doesn't care what your collection contains; it just needs you to follow the iteration rules.

The Two-Part Contract

The iterator protocol actually has two pieces:

The Iterable Protocol: An object is "iterable" if it has a method stored at the special key Symbol.iterator. When called, this method must return an iterator object.

The Iterator Protocol: The iterator object must have a next() method that returns an object with two properties:

  • value: the next item in the sequence
  • done: a boolean indicating whether iteration is complete

When you use for...of loops, array spreading, or destructuring, JavaScript automatically calls Symbol.iterator behind the scenes and repeatedly invokes next() until done is true.

Arrays, Strings, Maps, and Sets all follow this protocol, which is why they work seamlessly with iteration syntax.

Why It Matters

By defining a standard protocol rather than hardcoding iteration into the language, JavaScript lets any object participate in iteration—including your custom objects—as long as they implement the contract correctly.

Key Takeaway: The iterator protocol is JavaScript's contract for making objects iterable: implement Symbol.iterator to return an iterator with a next() method, and your object can work with all iteration features.