Learn JavaScript
❯ collections.iterables

Iterables & Iterators in JavaScript

$concept

Iterables (arrays, strings, Maps, Sets, generators, and custom [Symbol.iterator] objects) plug into for...of, spread, and destructuring through a single protocol: [Symbol.iterator]() returns an iterator whose next() yields {value, done} until done. One protocol unifies every sequential source in the language.

Custom iterables model lazy or infinite sequences (ranges, paginated APIs) without materializing arrays. Manual .next() calls drive step-by-step consumption; for...of hides the protocol for the common case.

$how it works
1

Protocol: Symbol.iterator

An object with [Symbol.iterator]() returning {next()} is iterable — for...of, spread, and destructuring all accept it.

2

next() yields {value, done}

Each call advances one step; done: true ends iteration — manual control when for...of is too blunt.

3

Lazy by nature

Values generate on demand — infinite ranges and paged fetches stream without upfront arrays.

4

Built-ins included

Arrays, strings, Maps, Sets, TypedArrays, and generators all implement the protocol natively.

$example
let range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let cur = this.from;
let last = this.to;
return { next() { return cur <= last ? { value: cur++, done: false } : { value: undefined, done: true }; } };
}
};
console.log([...range]);
Output
[ 1, 2, 3 ]
1The object defines iteration behavior — yielding 1, 2, 3 then done.
2Spread consumes the protocol fully into [1, 2, 3].
3Custom lazy sequences plug into every iterable-consuming syntax.
$use cases
Lazy ranges and paginated data without materializing arrays
Custom collections (trees, streams) with native for...of support
Manual stepping with .next() for coroutines and parsers
Unifying consumption across arrays, Maps, Sets, and generators

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.