Iterables & Iterators in JavaScript
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.
Protocol: Symbol.iterator
An object with [Symbol.iterator]() returning {next()} is iterable — for...of, spread, and destructuring all accept it.
next() yields {value, done}
Each call advances one step; done: true ends iteration — manual control when for...of is too blunt.
Lazy by nature
Values generate on demand — infinite ranges and paged fetches stream without upfront arrays.
Built-ins included
Arrays, strings, Maps, Sets, TypedArrays, and generators all implement the protocol natively.
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]);Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.