The Fibonacci series is a sequence where each number is the sum of the two preceding ones, starting from 0 and 1: 0, 1, 1, 2, 3, 5, 8, 13, 21 ... It’s one of the most common practice and interview problems because it can be solved in several different ways, each teaching a different concept — plain iteration and plain recursion being the two you’ll meet first.
JavaScript Program to Print Fibonacci Series (Using a Loop)
function fibonacciSeries(n) {
const series = [0, 1];
for (let i = 2; i < n; i++) {
series.push(series[i - 1] + series[i - 2]);
}
return series.slice(0, n);
}
console.log(fibonacciSeries(10).join(", "));
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
JavaScript Program to Print Fibonacci Series (Using Recursion)
The same series can be generated with a recursive approach, where each call to fib(n) returns the sum of the two previous terms.
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
const series = [];
for (let i = 0; i < 10; i++) series.push(fib(i));
console.log(series.join(", "));
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
The plain recursive version is simple to read but recalculates the same sub-problems over and over, so its time complexity is exponential — O(2^n). The loop version runs in O(n) and is the one you should actually use for anything beyond a teaching example; for larger series, an iterative or memoized approach is needed to avoid a noticeable slowdown once n climbs past the mid-30s with plain recursion.
