Build custom iterables with Symbol.iterator and create lazy sequences with generator functions. Understand how for...of and spread consume iterables.
Why: an iterator is any object with a next() method returning { value, done }. Arrays, strings, Maps, and Sets are all built-in iterables.
// Arrays are iterables — they implement [Symbol.iterator]
const arr = [10, 20, 30];
const iter = arr[Symbol.iterator]();
console.log(iter.next()); // { value: 10, done: false }
console.log(iter.next()); // { value: 20, done: false }
console.log(iter.next()); // { value: 30, done: false }
console.log(iter.next()); // { value: undefined, done: true }
// Custom iterable object
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
},
};
},
};
for (const n of range) process.stdout
? null // silence — use console.log below
: null;
const results = [...range];
console.log(results); // [1, 2, 3, 4, 5]Why: generator functions (function*) produce values lazily via yield. They pause execution and resume from where they left off — useful for infinite sequences and async iteration.
// Basic generator
function* count() {
yield 1;
yield 2;
yield 3;
}
const gen = count();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
// Infinite sequence — values computed on demand
function* naturals(start = 1) {
let n = start;
while (true) yield n++;
}
const nums = naturals();
console.log(nums.next().value); // 1
console.log(nums.next().value); // 2
console.log(nums.next().value); // 3
// Fibonacci generator
function* fibonacci() {
let [a, b] = [0, 1];
while (true) { yield a; [a, b] = [b, a + b]; }
}
const fibs = [];
for (const n of fibonacci()) {
fibs.push(n);
if (fibs.length === 9) break;
}
console.log(fibs); // [0, 1, 1, 2, 3, 5, 8, 13, 21]