Lazy iterator helpers
Quick answer
Iterator helpers transform or consume a sequence without first materializing the entire input. Lazy helpers do work when a consumer asks for results.
How it works
Use Iterator.from(source) to obtain a helper-capable iterator, then chain map, filter, take, drop or flatMap. Terminal operations such as toArray, reduce, forEach, find, some and every consume results. Place take before collecting an unbounded sequence; the order of filter and take changes which values count toward the limit. Helper objects are stateful, not reusable arrays. Check feature availability in the actual runtime; these examples run in Node.js 22.16.0.
const it=Iterator.from([1,2,3,4]).filter(n=>n%2===0).map(n=>n*10); console.log(JSON.stringify(it.take(1).toArray()));Expected output in Node.js:
[20]Only the first selected transformed value is collected.
let calls=0; const it=Iterator.from([1,2,3]).map(x=>{calls++;return x*2;}); console.log(calls);console.log(it.next().value,calls);Expected output in Node.js:
02 1Mapping is lazy and advances on demand.
Common mistakes
Never collect an unbounded iterator directly. A filter may not produce enough matches to terminate even with take after it. Use a finite source when learning.
Practice
Compare filtering before and after take on a finite range and explain the different outputs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lazy iterator helpers — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which helper limits the number of yielded elements?
Which listed operation materializes all remaining values?
What does a lazy map normally do before its first consumption?
What is the exact console output in Lazy iterator helpers example 1?
const it=Iterator.from([1,2,3,4]).filter(n=>n%2===0).map(n=>n*10); console.log(JSON.stringify(it.take(1).toArray()));What is the exact console output in Lazy iterator helpers example 2?
let calls=0; const it=Iterator.from([1,2,3]).map(x=>{calls++;return x*2;}); console.log(calls);console.log(it.next().value,calls);