JavaScript Iterator Helpers: Lazy map, filter and take
Array methods create a whole new array at each step. Iterator helpers work on iterators instead and are lazy: values are processed one at a time, only as many as you need.
The methods
iterator.map(fn) iterator.filter(fn) iterator.take(n)
iterator.drop(n) iterator.flatMap(fn) iterator.reduce(fn, init)
iterator.toArray() iterator.forEach(fn)
iterator.some(fn) iterator.every(fn) iterator.find(fn)
With generators
function* naturals() {
let n = 1;
while (true) yield n++; // infinite!
}
const firstSquaresOverHundred = naturals()
.map((n) => n * n)
.filter((sq) => sq > 100)
.take(3)
.toArray();
// [121, 144, 169] - only 13 numbers were ever generated
With arrays this would be impossible: you can't make an infinite array.
With Maps and Sets
const prices = new Map([['pen', 20], ['book', 450], ['bag', 1200]]);
const expensive = prices.entries()
.filter(([, price]) => price > 100)
.map(([name]) => name)
.toArray(); // ['book', 'bag']
No need for [...prices.entries()] first.
Processing large data lazily
function* lines(text) {
let start = 0;
for (let i = 0; i <= text.length; i++) {
if (i === text.length || text[i] === '\n') {
yield text.slice(start, i);
start = i + 1;
}
}
}
const firstErrors = lines(hugeLog)
.filter((l) => l.includes('ERROR'))
.take(5)
.toArray(); // stops scanning after the 5th error
Iterator.from
Wrap any iterable or iterator-like object to get the helpers: Iterator.from(someIterable).take(5).
Iterator helpers are part of ES2025 and supported in current browsers and Node.js 22+. Async iterators don't have these helpers yet.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.