What is lazy evaluation and infinite sequences in JavaScript?
Answer
Lazy evaluation defers computation until the result is actually needed, enabling efficient processing of large or infinite datasets by generating values on demand instead of upfront. JavaScript achieves lazy evaluation through generators and iterators. An infinite sequence using a generator: function* naturals(start = 0) { while(true) yield start++; } — never ends but is perfectly safe because values are produced only when requested. Take N values: function take(n, iterable) { const result = []; for (const item of iterable) { result.push(item); if (result.length >= n) break; } return result; }. Lazy pipelines: function* map(fn, iterable) { for (const x of iterable) yield fn(x); } function* filter(pred, iterable) { for (const x of iterable) if (pred(x)) yield x; } const first10EvenSquares = take(10, map(x => x**2, filter(x => x%2===0, naturals()))) — this processes elements lazily, only computing what is needed. Libraries like lazy.js and Lodash/fp provide lazy collection operations.
Previous
What are tagged template literals?
Next
What is the Abstract Equality Comparison algorithm?