Print Fibonacci Sequence in JavaScript (4 Methods)
The Fibonacci sequence is a list of numbers where each number is the result of adding the two numbers before it, starting with 0 and 1. It is a simple yet fascinating mathematical concept that appears in various fields, including nature and technology. It is defined as:
F(0) = 0, F(1) = 1
F(n) = F(n-1) + F(n-2), for n > 1
The sequence starts like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34...
This sequence is found in many areas, including math, computer science, and nature. It is commonly used in growth models, algorithm optimization, and solving problems with recursion.
In this guide, we will explore different ways to create the fibonacci sequence in JavaScript, using simple loops, recursion, and advanced methods like memoization. Whether you're learning basic fibonacci code in JavaScript or creating an optimized fibonacci series in JS, this tutorial will help you understand and apply the concepts effectively.
Fibonacci Sequence in JavaScript Using Iterative Approach
This is the simplest and most straightforward way to generate the Fibonacci sequence.
Code
function fibonacciIterative(n) {
if (n <= 0) return [];
if (n === 1) return [0];
let sequence = [0, 1];
for (let i = 2; i < n; i++) {
sequence.push(sequence[i - 1] + sequence[i - 2]);
}
return sequence;
}
// Test the function
const n = 10;
console.log(`Fibonacci sequence for ${n} terms:`, fibonacciIterative(n));
Output
Fibonacci sequence for 10 terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Explanation
-
The sequence starts with [0, 1].
-
A for loop calculates each subsequent term as the sum of the last two terms.
-
The result is stored in an array and returned.
Fibonacci Sequence Program in JavaScript Using Recursion
Recursion can also be used to calculate the Fibonacci sequence. Here, each term is computed by calling the function recursively.
Code
function fibonacciRecursive(n) {
if (n <= 0) return [];
if (n === 1) return [0];
if (n === 2) return [0, 1];
const sequence = fibonacciRecursive(n - 1);
sequence.push(sequence[sequence.length - 1] + sequence[sequence.length - 2]);
return sequence;
}
// Test the function
const n2 = 8;
console.log(`Fibonacci sequence in JS for ${n2} terms:`, fibonacciRecursive(n2));
Output
Fibonacci sequence in JS for 8 terms: [0, 1, 1, 2, 3, 5, 8, 13]
Explanation
-
The base cases handle sequences of lengths 0, 1, and 2.
-
The function calls itself for n-1 and appends the next Fibonacci term.
JavaScript Program to Print the Fibonacci Sequence Using Arrays
This approach uses an array explicitly to store the Fibonacci sequence.
Code
function fibonacciWithArray(n) {
if (n <= 0) return [];
let sequence = [0, 1];
while (sequence.length < n) {
const next = sequence[sequence.length - 1] + sequence[sequence.length - 2];
sequence.push(next);
}
return sequence;
}
// Test the function
const n3 = 6;
console.log(`Fibonacci sequence in JavaScript for ${n3} terms:`, fibonacciWithArray(n3));
Output
Fibonacci sequence in JavaScript for 6 terms: [0, 1, 1, 2, 3, 5]
Explanation
-
This method uses a while loop to generate terms until the desired length is reached.
-
Each new term is calculated as the sum of the last two terms in the array.
Print the Fibonacci Sequence in JavaScript Using Memoization
Memoization stores previously computed values to avoid redundant calculations and improve efficiency.
Code
function fibonacciMemoization(n, memo = { 0: 0, 1: 1 }) {
if (n in memo) return memo[n];
memo[n] = fibonacciMemoization(n - 1, memo) + fibonacciMemoization(n - 2, memo);
return memo[n];
}
function generateFibonacci(n) {
let sequence = [];
for (let i = 0; i < n; i++) {
sequence.push(fibonacciMemoization(i));
}
return sequence;
}
// Test the function
const n4 = 7;
console.log(`Fibonacci series in JS for ${n4} terms:`, generateFibonacci(n4));
Output
Fibonacci series in JS for 7 terms: [0, 1, 1, 2, 3, 5, 8]
Explanation
-
The memo object stores previously computed terms for faster retrieval.
-
The sequence is generated iteratively by calling the memoized function for each term.
Concepts Used in Above Programs
Iteration
-
Loops (for and while) are used to calculate terms efficiently in the iterative approach.
Recursion
-
Recursion simplifies the logic by breaking down the problem into smaller subproblems.
Arrays
-
Arrays are used to store the sequence and append new terms dynamically.
Memoization
-
Improves efficiency by storing results of expensive recursive calls.