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.
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
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
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; // 20Circular Buffer
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
// 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
// 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 Structure | Default Iteration | Alternative Traversals | Use Case |
|---|---|---|---|
| Linked List | Head to tail | Reversed, entries, filtered | Sequential data, queues |
| Binary Search Tree | In-order (sorted) | Pre-order, post-order, level-order, range | Sorted data, search |
| Circular Buffer | Oldest to newest | Newest to oldest | Fixed-size logs, buffers |
| Graph | All vertices | DFS, BFS, topological, edges | Networks, dependencies |
| Infinite Sequence | Start to infinity | take(), skip(), filter(), map() | Lazy computation |
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
Frequently Asked Questions
How do I make my class work with both for...of and array methods?
Should iterators be reusable or single-use?
How do I handle concurrent modification during iteration?
When should I use Symbol.asyncIterator instead of Symbol.iterator?
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.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.