JavaScript Snippet

Fibonacci: Iterative, Recursive, Memoized, Generator

Difficulty: Medium

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.

Code Snippets
/

Fibonacci: Iterative, Recursive, Memoized, Generator

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.

JavaScript
Medium
4 snippets
fibonacci
recursion
memoization
generators

808 views

14

Two variables (prev and curr) are all you need. Each iteration shifts forward: the destructuring assignment swaps them in one step without a temporary. Time is O(n) and extra memory is O(1). The sequence variant returns the full prefix as an array, useful when the caller wants to render every step or feed them into a chart. Above n = 78, the result exceeds Number.MAX_SAFE_INTEGER (2^53 - 1) and you start losing precision; promote to BigInt (0n, 1n, prev + curr) for arbitrary-precision integers.