Display Fibonacci Series in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Iteration

What you’ll learn

  • The usual programming definition starting from 0 and 1, with Fk = 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.

  • function declarations, const/let, and template literals or string concatenation.
  • Optional: BigInt literals (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).

Recurrence Fk=Fk-1+Fk-2
Seeds 0, 1
Growth ∼ φk

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.

First ten outputs

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 — matches Example 1 with n = 10.

Intuition

5+8 13
Rule
sum of prior pair
(a,b) shift
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.

Try 1, 15, or 80. Capped at 500 terms for this widget.

Live result
Press “Print series”.

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

Pseudocode
function print_first_n_fibonacci_terms(n):
    a = 0
    b = 1
    repeat n times:
        output a
        next = a + b
        a = b
        b = next
1

First 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.

JavaScript
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);
Try it Yourself

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.

2

All terms ≤ 100

Same recurrence, different stop rule: keep printing while the current value fits the ceiling. Output uses spaces (no comma run).

JavaScript
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);
Try it Yourself

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

Each term is the sum of the two before it. With seeds 0 and 1, the series begins 0, 1, 1, 2, 3, 5, 8, 13, ...
Yes; some texts start at F1=F2=1. The relative shift only changes indexing; the recurrence is the same after the first few values.
Fibonacci grows exponentially. JavaScript Number loses integer precision above Number.MAX_SAFE_INTEGER (2^53-1). Use BigInt or stop printing once values stop being safe integers.
Naive fib(n) recursion recomputes subproblems and is exponential in n. Iteration (or recursion with memoization) is O(n) time and O(1) extra space for streaming the series.
Printing zero terms is valid: print a header and no numbers, or treat n < 1 as an error depending on the assignment.
O(n) arithmetic steps with the two-pointer update, assuming each addition fits your chosen integer type.

🔄 Input / output examples

Change terms in Example 1 or maxVal in Example 2.

n (terms)Last printed (small demo)
10
21 (second is the second seed)
1034
471836311903 (still exact Number)
80Late 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.

Terms

n ≤ 0

Decide whether to print nothing, an error line, or to treat n = 0 as a valid empty series.

Precision

Unsafe next = a + b

Use BigInt, or guard with Number.isSafeInteger, before silent rounding.

Recursion

fib(n) tree

Exponential time if you recompute fib(n-1) and fib(n-2) independently; not suitable for long series.

Off-by-one

Counting prints

Clarify whether n counts printed numbers (this page) or iterations after the seeds.

⏱️ Time and space complexity

TaskTimeExtra space
First n terms (iterative)O(n)O(1)
All terms ≤ MO(k) prints, k = O(log M)O(1)
Naive fib(n) recursionO(φn) workO(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, and Number vs BigInt overflow.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful