Skip to content
Concept 64 // Module 07: Collections, Iteration & Modules

Iterable & Iterator Protocols

Module 07: Collections, Iteration & Modules•Concept 64 of 100• 5 min read

Iterable & Iterator Protocols

JavaScript's **Iteration Protocols** allow any object to define or customize its iteration behavior. The **Iterable** protocol allows objects to be used in `for...of` loops, while the **Iterator** protocol defines how values are produced.

The Core Concept

Syntax Reference
// 1. The Iterator Protocol
// An object with a next() method
const iterator = {
  next() {
    return { value: 1, done: false };
  }
};

// 2. The Iterable Protocol
// An object with [Symbol.iterator]
const myIterable = {
  [Symbol.iterator]() {
    return iterator;
  }
};

Live Interactive Studio

By implementing `[Symbol.iterator]`, we make the `range` object compatible with `for...of`, even though it's not an Array.
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

Custom Range Iterator

// 1. Custom Range Iterator
const range = {
  from: 1,
  to: 3,
  [Symbol.iterator]() {
    this.current = this.from;
    return this;
  },
  next() {
    if (this.current <= this.to) {
      return { done: false, value: this.current++ };
    } else {
      return { done: true };
    }
  }
};

for (let num of range) {
  console.log(num); // 1, 2, 3
}
By implementing `[Symbol.iterator]`, we make the `range` object compatible with `for...of`, even though it's not an Array.
02

String Iteration

// 2. String Iteration
const str = "Hi";
const iter = str[Symbol.iterator]();

console.log(iter.next()); // { value: 'H', done: false }
console.log(iter.next()); // { value: 'i', done: false }
console.log(iter.next()); // { value: undefined, done: true }
Strings are built-in iterables. You can manually request their iterator and 'walk' through the characters one by one.
03

Spread & Iteration

// 3. Spread & Iteration
const nums = [1, 2];
const doubled = [...nums, 3]; // Uses iteration protocol

// The spread operator (...) works on ANY iterable, 
// not just arrays!
Many modern JS features like spread and destructuring rely internally on these protocols to fetch data from objects.
04

1. Core Usage: Iterable & Iterator Protocols

// Core syntax and usage for Iterable & Iterator Protocols
const feature = 'iterable-iterator-protocols';
console.log('Concept 64:', feature);
console.log('Active:', true);
Illustrates the fundamental invocation and syntax structure for Iterable & Iterator Protocols.
05

2. Defensive Handling & Edge Case

// Edge-case defensive handling
function handleSafe(input) {
  if (input === null || input === undefined) return 'safe-fallback';
  return String(input).trim();
}
console.log(handleSafe('iterable-iterator-protocols'));
console.log(handleSafe(null));
Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with Iterable & Iterator Protocols.
06

3. Clean Architecture & Production Pattern

// Production-grade pattern for Iterable & Iterator Protocols
const settings = Object.freeze({
  id: 'iterable-iterator-protocols',
  ready: true,
  timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);
Demonstrates clean, immutable production code avoiding unintended state mutations.

Real-World Engineering Takeaways

Custom Collections: Creating trees or linked lists that can be looped over.
Infinite Streams: Generating numbers on-the-fly without storing them in memory.
Lazy Evaluation: Calculating values only when they are requested by the loop.
Compatibility: Making your custom data structures work with standard JS tools like `Array.from()`.

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
### **Memory & State** **1. Iterator State:** - The Iterator maintains its **Internal State** (like `this.current`) in the **Heap**. - Unlike an Array, it doesn't need to store all items at once. It only stores the **Current Index**. **2. Symbolic Lookup:** - `Symbol.iterator` is a unique key in the **RAM**. - Using a Symbol prevents collisions with other property names on your object. **3. CPU Overhead:** - Each step of a `for...of` loop involves a function call to `next()`. - **Performance:** For high-frequency loops, standard `for` loops with indices are faster because they avoid the overhead of the Iterator object and function calls.

Quick Knowledge Check

Test your understanding on these 10 questions (one by one):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

What is the core purpose of Iterable & Iterator Protocols in JavaScript?

// Concept 64: Iterable & Iterator Protocols
// Understanding the core mental model
1 / 10