Creating JavaScript Custom Iterables Full Guide

Learn to build custom iterable data structures in JavaScript. Covers linked lists, trees, graphs, skip lists, priority queues, circular buffers, infinite streams, range objects, and bidirectional iterables with complete Symbol.iterator implementations.

JavaScriptadvanced
18 min read

Custom iterables open the full power of JavaScript's iteration ecosystem to your data structures. Once you implement [Symbol.iterator](), your collections work with for...of, spread, destructuring, Array.from(), and every API that consumes iterables.

For the iterator protocol details, see Advanced JavaScript Iterators Complete Guide.

Iterable Linked List

javascriptjavascript
class LinkedListNode {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}
 
class LinkedList {
  #head = null;
  #tail = null;
  #size = 0;
 
  append(value) {
    const node = new LinkedListNode(value);
    if (!this.#head) {
      this.#head = node;
      this.#tail = node;
    } else {
      this.#tail.next = node;
      this.#tail = node;
    }
    this.#size++;
    return this;
  }
 
  prepend(value) {
    const node = new LinkedListNode(value, this.#head);
    this.#head = node;
    if (!this.#tail) this.#tail = node;
    this.#size++;
    return this;
  }
 
  get length() {
    return this.#size;
  }
 
  // Core iterable implementation
  [Symbol.iterator]() {
    let current = this.#head;
 
    return {
      next() {
        if (current === null) {
          return { value: undefined, done: true };
        }
        const value = current.value;
        current = current.next;
        return { value, done: false };
      },
 
      // Support early exit cleanup
      return() {
        current = null; // Release reference
        return { value: undefined, done: true };
      }
    };
  }
 
  // Additional iteration methods
  *reversed() {
    // Collect nodes then yield in reverse
    const nodes = [...this];
    for (let i = nodes.length - 1; i >= 0; i--) {
      yield nodes[i];
    }
  }
 
  *entries() {
    let index = 0;
    for (const value of this) {
      yield [index++, value];
    }
  }
 
  *filter(predicate) {
    for (const value of this) {
      if (predicate(value)) yield value;
    }
  }
 
  *map(fn) {
    for (const value of this) {
      yield fn(value);
    }
  }
 
  static from(iterable) {
    const list = new LinkedList();
    for (const item of iterable) {
      list.append(item);
    }
    return list;
  }
}
 
const list = new LinkedList();
list.append(10).append(20).append(30).append(40);
 
// for...of
for (const val of list) {
  console.log(val); // 10, 20, 30, 40
}
 
// Spread
console.log([...list]); // [10, 20, 30, 40]
 
// Destructuring
const [first, second, ...rest] = list;
console.log(first, second, rest); // 10 20 [30, 40]
 
// Array.from
console.log(Array.from(list)); // [10, 20, 30, 40]
 
// Chained lazy operations
console.log([...list.filter(n => n > 15).map(n => n * 2)]); // [40, 60, 80]
 
// From any iterable
const fromArray = LinkedList.from([1, 2, 3]);
const fromSet = LinkedList.from(new Set([4, 5, 6]));

Iterable Binary Tree

javascriptjavascript
class BSTNode {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}
 
class BinarySearchTree {
  #root = null;
  #size = 0;
 
  insert(value) {
    const node = new BSTNode(value);
 
    if (!this.#root) {
      this.#root = node;
      this.#size++;
      return this;
    }
 
    let current = this.#root;
    while (true) {
      if (value < current.value) {
        if (!current.left) { current.left = node; break; }
        current = current.left;
      } else if (value > current.value) {
        if (!current.right) { current.right = node; break; }
        current = current.right;
      } else {
        return this; // Duplicate
      }
    }
 
    this.#size++;
    return this;
  }
 
  get length() {
    return this.#size;
  }
 
  // Default: in-order traversal (sorted)
  [Symbol.iterator]() {
    return this.inOrder();
  }
 
  // In-order: left, root, right (sorted)
  *inOrder(node = this.#root) {
    if (!node) return;
    yield* this.inOrder(node.left);
    yield node.value;
    yield* this.inOrder(node.right);
  }
 
  // Pre-order: root, left, right
  *preOrder(node = this.#root) {
    if (!node) return;
    yield node.value;
    yield* this.preOrder(node.left);
    yield* this.preOrder(node.right);
  }
 
  // Post-order: left, right, root
  *postOrder(node = this.#root) {
    if (!node) return;
    yield* this.postOrder(node.left);
    yield* this.postOrder(node.right);
    yield node.value;
  }
 
  // Level-order (BFS)
  *levelOrder() {
    if (!this.#root) return;
    const queue = [this.#root];
 
    while (queue.length > 0) {
      const node = queue.shift();
      yield node.value;
 
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
 
  // Range query: yield values in [min, max]
  *range(min, max, node = this.#root) {
    if (!node) return;
    if (node.value > min) yield* this.range(min, max, node.left);
    if (node.value >= min && node.value <= max) yield node.value;
    if (node.value < max) yield* this.range(min, max, node.right);
  }
}
 
const bst = new BinarySearchTree();
bst.insert(50).insert(30).insert(70).insert(20).insert(40).insert(60).insert(80);
 
console.log([...bst]);          // [20, 30, 40, 50, 60, 70, 80] (sorted)
console.log([...bst.preOrder()]);  // [50, 30, 20, 40, 70, 60, 80]
console.log([...bst.levelOrder()]); // [50, 30, 70, 20, 40, 60, 80]
console.log([...bst.range(35, 65)]); // [40, 50, 60]
 
// Works with all iterable consumers
const min = Math.min(...bst); // 20
const [smallest] = bst;       // 20

Circular Buffer

javascriptjavascript
class CircularBuffer {
  #buffer;
  #capacity;
  #head = 0;
  #tail = 0;
  #size = 0;
 
  constructor(capacity) {
    this.#capacity = capacity;
    this.#buffer = new Array(capacity);
  }
 
  push(item) {
    this.#buffer[this.#tail] = item;
    this.#tail = (this.#tail + 1) % this.#capacity;
 
    if (this.#size === this.#capacity) {
      // Overwrite oldest: advance head
      this.#head = (this.#head + 1) % this.#capacity;
    } else {
      this.#size++;
    }
 
    return this;
  }
 
  shift() {
    if (this.#size === 0) return undefined;
 
    const value = this.#buffer[this.#head];
    this.#buffer[this.#head] = undefined;
    this.#head = (this.#head + 1) % this.#capacity;
    this.#size--;
    return value;
  }
 
  peek() {
    return this.#size > 0 ? this.#buffer[this.#head] : undefined;
  }
 
  get length() {
    return this.#size;
  }
 
  get capacity() {
    return this.#capacity;
  }
 
  isFull() {
    return this.#size === this.#capacity;
  }
 
  [Symbol.iterator]() {
    let index = 0;
    const buffer = this.#buffer;
    const head = this.#head;
    const size = this.#size;
    const capacity = this.#capacity;
 
    return {
      next() {
        if (index >= size) {
          return { value: undefined, done: true };
        }
        const pos = (head + index) % capacity;
        index++;
        return { value: buffer[pos], done: false };
      }
    };
  }
 
  // Iterate from newest to oldest
  *reversed() {
    for (let i = this.#size - 1; i >= 0; i--) {
      const pos = (this.#head + i) % this.#capacity;
      yield this.#buffer[pos];
    }
  }
 
  toString() {
    return `CircularBuffer(${[...this].join(", ")})`;
  }
}
 
const buffer = new CircularBuffer(5);
buffer.push("a").push("b").push("c").push("d").push("e");
console.log([...buffer]); // ["a", "b", "c", "d", "e"]
 
buffer.push("f"); // Overwrites "a"
console.log([...buffer]); // ["b", "c", "d", "e", "f"]
 
buffer.push("g"); // Overwrites "b"
console.log([...buffer.reversed()]); // ["g", "f", "e", "d", "c"]

Infinite and Lazy Sequences

javascriptjavascript
// Infinite iterables that compute values on demand
 
class InfiniteSequence {
  #generator;
 
  constructor(generator) {
    this.#generator = generator;
  }
 
  [Symbol.iterator]() {
    return this.#generator();
  }
 
  take(n) {
    const gen = this.#generator;
    return new FiniteSequence(function* () {
      let count = 0;
      for (const value of gen()) {
        if (count >= n) return;
        yield value;
        count++;
      }
    });
  }
 
  map(fn) {
    const gen = this.#generator;
    return new InfiniteSequence(function* () {
      for (const value of gen()) {
        yield fn(value);
      }
    });
  }
 
  filter(predicate) {
    const gen = this.#generator;
    return new InfiniteSequence(function* () {
      for (const value of gen()) {
        if (predicate(value)) yield value;
      }
    });
  }
 
  skip(n) {
    const gen = this.#generator;
    return new InfiniteSequence(function* () {
      let count = 0;
      for (const value of gen()) {
        if (count >= n) yield value;
        count++;
      }
    });
  }
}
 
class FiniteSequence extends InfiniteSequence {
  toArray() {
    return [...this];
  }
 
  reduce(fn, initial) {
    let acc = initial;
    for (const value of this) {
      acc = fn(acc, value);
    }
    return acc;
  }
}
 
// FIBONACCI SEQUENCE
const fibonacci = new InfiniteSequence(function* () {
  let a = 0, b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
});
 
console.log(fibonacci.take(8).toArray()); // [0, 1, 1, 2, 3, 5, 8, 13]
 
console.log(
  fibonacci
    .filter(n => n % 2 === 0)
    .take(5)
    .toArray()
); // [0, 2, 8, 34, 144]
 
// PRIME SIEVE
const primes = new InfiniteSequence(function* () {
  function isPrime(n) {
    if (n < 2) return false;
    for (let i = 2; i * i <= n; i++) {
      if (n % i === 0) return false;
    }
    return true;
  }
 
  let n = 2;
  while (true) {
    if (isPrime(n)) yield n;
    n++;
  }
});
 
console.log(primes.take(10).toArray()); // [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
 
// RANDOM WALK
const randomWalk = new InfiniteSequence(function* () {
  let position = 0;
  while (true) {
    position += Math.random() > 0.5 ? 1 : -1;
    yield position;
  }
});
 
console.log(randomWalk.take(10).toArray()); // [1, 0, -1, 0, 1, 2, 1, 0, -1, -2] (varies)

Multi-Iteration Support

javascriptjavascript
// Iterable graph with multiple traversal strategies
 
class Graph {
  #adjacency = new Map();
 
  addEdge(from, to) {
    if (!this.#adjacency.has(from)) this.#adjacency.set(from, new Set());
    if (!this.#adjacency.has(to)) this.#adjacency.set(to, new Set());
    this.#adjacency.get(from).add(to);
    return this;
  }
 
  // Default iteration: yield all vertices
  [Symbol.iterator]() {
    return this.#adjacency.keys();
  }
 
  // DFS traversal from a start node
  *dfs(start) {
    const visited = new Set();
    const stack = [start];
 
    while (stack.length > 0) {
      const node = stack.pop();
      if (visited.has(node)) continue;
 
      visited.add(node);
      yield node;
 
      const neighbors = this.#adjacency.get(node);
      if (neighbors) {
        for (const neighbor of neighbors) {
          if (!visited.has(neighbor)) {
            stack.push(neighbor);
          }
        }
      }
    }
  }
 
  // BFS traversal from a start node
  *bfs(start) {
    const visited = new Set([start]);
    const queue = [start];
 
    while (queue.length > 0) {
      const node = queue.shift();
      yield node;
 
      const neighbors = this.#adjacency.get(node);
      if (neighbors) {
        for (const neighbor of neighbors) {
          if (!visited.has(neighbor)) {
            visited.add(neighbor);
            queue.push(neighbor);
          }
        }
      }
    }
  }
 
  // Yield edges as [from, to] pairs
  *edges() {
    for (const [from, neighbors] of this.#adjacency) {
      for (const to of neighbors) {
        yield [from, to];
      }
    }
  }
 
  // Topological sort (for DAGs)
  *topologicalSort() {
    const inDegree = new Map();
    for (const node of this.#adjacency.keys()) {
      if (!inDegree.has(node)) inDegree.set(node, 0);
    }
    for (const [, neighbors] of this.#adjacency) {
      for (const n of neighbors) {
        inDegree.set(n, (inDegree.get(n) || 0) + 1);
      }
    }
 
    const queue = [];
    for (const [node, degree] of inDegree) {
      if (degree === 0) queue.push(node);
    }
 
    while (queue.length > 0) {
      const node = queue.shift();
      yield node;
 
      const neighbors = this.#adjacency.get(node);
      if (neighbors) {
        for (const neighbor of neighbors) {
          const newDegree = inDegree.get(neighbor) - 1;
          inDegree.set(neighbor, newDegree);
          if (newDegree === 0) queue.push(neighbor);
        }
      }
    }
  }
}
 
const graph = new Graph();
graph.addEdge("A", "B").addEdge("A", "C").addEdge("B", "D")
     .addEdge("C", "D").addEdge("D", "E");
 
console.log([...graph.bfs("A")]);            // ["A", "B", "C", "D", "E"]
console.log([...graph.dfs("A")]);            // ["A", "C", "D", "E", "B"] (varies)
console.log([...graph.edges()]);             // [["A","B"],["A","C"],["B","D"],...]
console.log([...graph.topologicalSort()]);   // ["A", "B", "C", "D", "E"]
Data StructureDefault IterationAlternative TraversalsUse Case
Linked ListHead to tailReversed, entries, filteredSequential data, queues
Binary Search TreeIn-order (sorted)Pre-order, post-order, level-order, rangeSorted data, search
Circular BufferOldest to newestNewest to oldestFixed-size logs, buffers
GraphAll verticesDFS, BFS, topological, edgesNetworks, dependencies
Infinite SequenceStart to infinitytake(), skip(), filter(), map()Lazy computation
Rune AI

Rune AI

Key Insights

  • Implement Symbol.iterator to make any object work with for...of, spread, destructuring, and Array.from(): Return a new iterator each time to support multiple concurrent iterations
  • Generator methods (function) provide the simplest way to implement multiple traversal strategies on a single collection*: Yield from recursive generators using yield* for tree and graph traversals
  • Circular buffers demonstrate iterating over non-contiguous memory by computing positions with modular arithmetic: The iterator captures head position and size at creation time for consistent snapshots
  • Infinite sequences composed with lazy map, filter, and take enable functional programming over unbounded data: No intermediate arrays are created and computation stops as soon as take() is satisfied
  • Graph iterables support multiple traversals (DFS, BFS, topological sort) as separate generator methods while using vertex iteration as the default: Each traversal maintains its own visited set and queue/stack state
RunePowered by Rune AI

Frequently Asked Questions

How do I make my class work with both for...of and array methods?

Implement `[Symbol.iterator]()` to enable `for...of`, spread, and destructuring. For array methods (`map`, `filter`, `reduce`), either convert to an array with `[...this]` or `Array.from(this)`, or add generator-based methods to your class that return new iterables. The lazy approach (generator methods) is preferred for large collections because it avoids creating intermediate arrays. You can also extend your class with a fluent API that wraps generators.

Should iterators be reusable or single-use?

Iterables should be reusable (produce fresh iterators on each call to `[Symbol.iterator]()`). Iterators themselves are typically single-use. This distinction is important: if your iterator IS the iterable (returns itself from `[Symbol.iterator]()`), it can only be iterated once. Design your collection classes to return a new iterator object each time, allowing multiple concurrent iterations and repeated traversal. Generators are naturally single-use, so wrap them in iterable objects for reusability.

How do I handle concurrent modification during iteration?

The safest approach is to snapshot the collection state when creating the iterator. Copy the relevant data (array of items, head pointer, etc.) into the iterator closure. This prevents issues when items are added or removed during iteration. An alternative is fail-fast detection: track a modification counter on the collection and check it in each `next()` call, throwing if the collection was modified. Java's `ConcurrentModificationException` follows this pattern.

When should I use Symbol.asyncIterator instead of Symbol.iterator?

Use `Symbol.asyncIterator` when producing each value requires asynchronous work: fetching from an API, reading from a stream, querying a database, or waiting for events. If your values are computed synchronously (even if the collection was loaded asynchronously), use `Symbol.iterator`. A common mistake is using async iterators for data already in memory. The async iterator protocol adds overhead (promise creation, microtask scheduling) that is unnecessary for synchronous data.

Conclusion

Custom iterables transform data structures into first-class citizens of JavaScript's iteration ecosystem. Linked lists, trees, graphs, and infinite sequences all benefit from implementing [Symbol.iterator](). For the underlying protocol mechanics, revisit Advanced JavaScript Iterators Complete Guide. For metaprogramming techniques that can dynamically add iteration support, see JS Metaprogramming Advanced Architecture Guide.