Generators
generators
Code Snippets
Generate a Numeric Range
JavaScript still has no built-in `range()` like Python, so every codebase eventually grows its own. This snippet shows the canonical `Array.from` trick for `[0, n)`, a `start, end, step` variant that handles negative steps, and a lazy generator for huge ranges where allocating the full array is wasteful. Use it for pagination, retries, table rows, and any test fixture that needs N of something.
Fibonacci: Iterative, Recursive, Memoized, Generator
Fibonacci is the canonical exercise for comparing iteration, recursion, memoization, and lazy evaluation. The iterative for-loop is the production answer, naive recursion is the cautionary tale (exponential cost), memoization fixes the recursion to linear time, and a generator yields an infinite stream you can `take(n)` from. Above index 78, switch to BigInt to avoid floating-point precision loss.
Generators as State Machines
Generators turn an explicit `switch (state)` block into a function whose own pause points encode the state. This snippet shows three flavors: a finite-state machine driven by `next(event)` for transitions, a step-by-step async sequencer that pauses between phases, and a richer machine with entry/exit side effects plus an unexpected-event handler. Reach for this when your control flow has a small, explicit set of states and you want the language to enforce them for you.
Question Banks
JavaScript Class, Generator, and Strict-Mode Traces
Four advanced traces covering generator iterator state, the `_id` private-by-convention pattern, strict mode + `Object.defineProperty` enumerability, and try/catch + `var` scope leaks.
Generators and Iterators Quiz
Practice the iterator protocol from both sides: write an infinite Fibonacci generator, an async iterable, a `[Symbol.iterator]` implementation, and a `for...of` consumer.
