- Rule
- sum of prior pair
Display Fibonacci Series in JavaScript
What you’ll learn
- The usual programming definition starting from
0and1, withFk = Fk-1 + Fk-2. - An
n-term printer matching the reference flow, with clean separators (no stray trailing comma). - A second pattern: print every Fibonacci number up to a ceiling, plus overflow notes and a live preview using
BigInt.
Overview
The Fibonacci sequence is the hello-world of stateful loops: two variables hold the previous pair, each iteration prints (or stores) one value and advances the pair forward.
Two programs
Ten terms (0 … 34) and values ≤ 100.
Live preview
First n terms with BigInt in the browser (no silent float rounding).
Rigor
Nonpositive term counts, Number precision limits, and why naive recursion is avoided for series.
Prerequisites
for / while loops, console.log, and integer addition.
functiondeclarations,const/let, and template literals or string concatenation.- Optional:
BigIntliterals (0n) for exact long series in modern engines.
What is the Fibonacci series?
Starting from 0 and 1, every later term is the sum of the previous two. This tutorial prints terms in that order.
The sequence appears in rabbit models, tiling counts, continued fractions, and algorithm analysis (Fibonacci heaps, matrix powers, and Euclid’s algorithm worst case).
Golden ratio bound
Let φ = (1+√5)/2. Then Fk with the usual nonnegative indexing satisfies Fk ∼ φk / √5 as k → ∞, explaining rapid growth in fixed-width types.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 — matches Example 1 with n = 10.
Intuition
- Update
(a,b)←(b,a+b)
Takeaway: you only need two accumulators to stream the sequence; no array is required for printing.
Live preview
First n terms with 0, 1 seeds. Uses BigInt so long series stay exact in the browser.
Algorithm
Goal: print the first n Fibonacci numbers in order, or every Fibonacci number not exceeding a bound M.
Initialize the pair
Set (first, second) = (0, 1) to match this tutorial’s seed convention.
Iterate
Print first, compute next = first + second, then shift (first, second) ← (second, next). Stop after n prints or when the next value would exceed M.
📜 Pseudocode
function print_first_n_fibonacci_terms(n):
a = 0
b = 1
repeat n times:
output a
next = a + b
a = b
b = nextFirst n terms (n = 10)
Same logic as the reference (displayFibonacci): two-pointer update and terms = 10. Adds n ≤ 0 handling and avoids a trailing comma after the last term.
function displayFibonacciTerms(n) {
if (n <= 0) {
console.log("Need a positive term count.");
return;
}
let first = 0;
let second = 1;
const parts = [];
for (let i = 0; i < n; i++) {
parts.push(String(first));
const next = first + second;
first = second;
second = next;
}
console.log(
"Fibonacci series up to " + n + " terms: " + parts.join(", ")
);
}
const terms = 10;
displayFibonacciTerms(terms);Explanation
The loop collects each first before advancing the pair. Joining with ", " avoids the dangling comma some printf-only layouts leave after the last term.
All terms ≤ 100
Same recurrence, different stop rule: keep printing while the current value fits the ceiling. Output uses spaces (no comma run).
function displayFibonacciUntil(maxVal) {
if (maxVal < 0) {
console.log("max_val must be nonnegative.");
return;
}
let a = 0;
let b = 1;
const parts = [];
while (a <= maxVal) {
parts.push(String(a));
const next = a + b;
a = b;
b = next;
}
console.log(
"Fibonacci numbers <= " + maxVal + ": " + parts.join(" ")
);
}
displayFibonacciUntil(100);Explanation
The loop condition checks the value about to be printed. The first Fibonacci strictly greater than 100 is 144, so the series stops at 89.
Going faster (optional)
Matrix exponentiation. Computes Fn in O(log n) arithmetic steps using [[1,1],[1,0]] powers—overkill for printing the whole prefix.
Doubling identities. Useful in competitive programming for huge n modulo a prime.
Interview: prefer the O(n) two-pointer loop; mention overflow and why tree recursion is avoided.
❓ FAQ
🔄 Input / output examples
Change terms in Example 1 or maxVal in Example 2.
| n (terms) | Last printed (small demo) |
|---|---|
1 | 0 |
2 | 1 (second is the second seed) |
10 | 34 |
47 | 1836311903 (still exact Number) |
80 | Late terms exceed Number.MAX_SAFE_INTEGER; use BigInt for exact long runs |
Edge cases and pitfalls
JavaScript Number arithmetic becomes imprecise once Fibonacci values exceed Number.MAX_SAFE_INTEGER. Prefer BigInt or stop printing.
n ≤ 0
Decide whether to print nothing, an error line, or to treat n = 0 as a valid empty series.
Unsafe next = a + b
Use BigInt, or guard with Number.isSafeInteger, before silent rounding.
fib(n) tree
Exponential time if you recompute fib(n-1) and fib(n-2) independently; not suitable for long series.
Counting prints
Clarify whether n counts printed numbers (this page) or iterations after the seeds.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
First n terms (iterative) | O(n) | O(1) |
All terms ≤ M | O(k) prints, k = O(log M) | O(1) |
Naive fib(n) recursion | O(φn) work | O(n) stack |
Here φ is the golden ratio; the exponential bound is the classic analysis of the naive tree.
Summary
- Core loop: print
first, then(first,second)←(second,first+second). - Variants: fixed term count vs values bounded by
M. - Watch-outs:
n ≤ 0, formatting, andNumbervsBigIntoverflow.
The ratio of consecutive values Fk+1/Fk (for positive Fk) approaches the golden ratio φ = (1+√5)/2 as k grows—one reason Fibonacci numbers explode so quickly in fixed-precision types.
8 people found this page helpful
