Sub topic 1
Iterables and Iterators: A Quick Refresher
Prerequisites
This chapter assumes you know modern JavaScript syntax (arrow functions, const/let, spread), Array methods such as map and filter, for...of loops, and generator functions (function*).
The Iteration Protocol
An iterable is an object with a [Symbol.iterator]() method. An iterator is an object with a next() method that returns { value, done }. Arrays, strings, Maps, and Sets are iterables. Calling [Symbol.iterator]() on one of them gives you an iterator. for...of and spread follow this protocol under the hood.
Where Iterator Helpers Live: Iterator.prototype
ES2025 added map, filter, take, drop, and other helper methods to Iterator.prototype. Generator objects and built-in iterators inherit from it. These include the iterators returned by array.values(), map.entries(), and string[Symbol.iterator](). Arrays are iterables, not iterators, so [1, 2].map is still the eager Array method. To get the lazy version, call .values() first.
function* gen() { yield 1; }
console.log(typeof gen().map); // 'function'
console.log(typeof [1].values().filter); // 'function'Lazy Evaluation: Nothing Runs Until You Pull
A helper returns a new iterator right away and does no work yet. Each call to next() pulls one value through the chain. Your callbacks run only during that pull.
const it = [1, 2, 3].values().map((x) => {
console.log('mapping', x);
return x * 2;
});
console.log('created');
console.log(it.next().value);
// created
// mapping 1
// 2Transforming Values with map
map(fn) yields fn(value) for each source value. It pulls one source value for each output value, which means it works on any iterator, including infinite ones.
Selecting Values with filter
filter(fn) yields only the values for which fn returns a truthy result. A single next() call on a filter can pull several source values until one passes.
function* naturals() {
let n = 0;
while (true) yield n++;
}
const evens = naturals().filter((n) => n % 2 === 0);
console.log(evens.next().value); // 0
console.log(evens.next().value); // 2Exercise
In const it = [5, 6, 7].values().filter((n) => { console.log('check', n); return n > 5; });, what is logged by the line itself, and what is logged by a following it.next()?
Show answer
The line logs nothing, because filter is lazy. The it.next() call logs "check 5" and then "check 6", and it returns { value: 6, done: false }.