How to calculate the Fibonacci series in JavaScript ?
Last Updated :
14 Mar, 2024
Fibonacci series is a number series that contains integers in the following pattern.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ..
In terms of mathematics, the general formula for calculating the Fibonacci series is
fn = fn-1 + fn-2 , where n ≥ 2
Here, f0 = 0 and f1 = 1.
We need to calculate n Fibonacci numbers for any given integer n, where n ≥ 0.
Example:
Input : n = 5
Output : [0, 1, 1, 2, 3]
Input : n = 10
Output : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
In this article, we are focusing on two major and common ways for calculating the Fibonacci series.
Using Loop
The method of calculating Fibonacci Series using this method is better as compared to the recursive method. This method makes use of Dynamic Programming which works by storing the number generated so far and then using it for further calculations.
As the number for n=1 and n=2 are fixed, i.e, 0 and 1, then the rest of the numbers in the series can be calculated by the logic,
f3 = f2 + f1
f4 = f3 + f2
f5 = f4 + f3
...
fn = fn-1 + fn-2
This logic can be implemented using for as well as the while loop in JavaScript.
Using for Loop
As the first two values of the series are fixed, we start the loop with i = 2 and iterate until i < n, because array indexing starts at 0, so, n = 1 will technically mean i = 0 in case of arrays.
JavaScript
const n = 10;
// Create a new array of size 'n'
let series = new Array(n);
// Fills all places in array with 0
series.fill(0);
// Seed value for 1st element
series[0] = 0;
// Seed value for 2nd element
series[1] = 1;
for (let i = 2; i < n; i++) {
// Apply basic Fibonacci formulae
series[i] = series[i - 1] + series[i - 2];
}
// Print the series
console.log(series);
Output[
0, 1, 1, 2, 3,
5, 8, 13, 21, 34
]
Using while Loop
JavaScript
const n = 10;
// Create a new array of size 'n'
let series = new Array(n);
// Fills all places in array with 0
series.fill(0);
// Seed value for 1st element
series[0] = 0;
// Seed value for 2nd element
series[1] = 1;
// Initialize the conditional variable
let i = 2;
while (i < n) {
// Apply basic Fibonacci formulae
series[i] = series[i - 1] + series[i - 2];
// Increment the conditional variable
i++;
}
// Print the series
console.log(series);
Output[
0, 1, 1, 2, 3,
5, 8, 13, 21, 34
]
The recursion method to print the whole Fibonacci series till a certain number is not recommended because, recursion algorithm itself is costly in terms of time and complexity, and along with fetching a Fibonacci series number at a certain position, we need to store them in an array, which calls the recursive function again and again for each and every element, i.e, n times!
The recursion method can be applied as follows in JavaScript.
JavaScript
function fibonacci(n) {
// Return value for n = 1
if (n == 1) return 0;
// Return value for n = 2
if (n == 2) return 1;
// Recursive call
return fibonacci(n - 1) + fibonacci(n - 2);
}
const n = 10;
// Create a new array of size 'n'
let series = new Array(n);
// Fills all places in array with 0
series.fill(0);
for (let i = 1; i <= n; i++) {
// Store i-th Fibonacci number
series[i - 1] = fibonacci(i);
}
// Print the series
console.log(series);
Output[
0, 1, 1, 2, 3,
5, 8, 13, 21, 34
]
Similar Reads
How to Add the Numbers in a JavaScript Array?
Adding the numbers in a JavaScript array is a common operation, particularly in tasks involving data aggregation or mathematical calculations. This process involves iterating through the array and summing its elements. JavaScript provides multiple methods to achieve this, ranging from traditional lo
2 min read
How to Check if a Given Number is Fibonacci Number in JavaScript ?
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. Checking for Fibonacci numbers involves verifying whether a given number appears in this sequence. The first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and
4 min read
How to Format a Float in JavaScript?
Formatting a float number means rounding off a number up to a given number of decimal places. Below are the approaches to format a float in JavaScript: Table of ContentUsing Math.ceil() methodUsing toFixed() methodUsing Math.round() methodUsing Math.floor() MethodUsing float.toExponential() methodUs
3 min read
How to Calculate the Number of Days between Two Dates in JavaScript?
Calculating the number of days between two dates is a common task in web development, especially when working with schedules, deadlines, or event planning. JavaScript provides a simple and effective way to perform this calculation by using different approaches. Whether you're comparing past and futu
4 min read
How to write a function in JavaScript ?
JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read
How to Find the Sum of an Array of Numbers in JavaScript ?
To find the sum of an array of numbers in JavaScript, you can use several different methods.1. Using Array reduce() MethodThe array reduce() method can be used to find the sum of array. It executes the provided code for all the elements and returns a single output.Syntaxarr.reduce( callback( acc, el
2 min read
How to convert string into float in JavaScript?
In this article, we will convert a string into a float in Javascript. We can convert a string into a float in JavaScript by using some methods which are described below: Methods to Concert String into Float:Table of Content Method 1: By using Type Conversion of JavaScriptMethod 2: By using parseFloa
6 min read
JavaScript Program to print Fibonacci Series
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms. The recurrence relation defines the sequence Fn of Fibonacci numbers:Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1Examples:Input : 5
4 min read
How to transform String into a function in JavaScript ?
In this article, we will see how to transform a String into a function in JavaScript. There are two ways to transform a String into a function in JavaScript. The first and easy one is eval() but it is not a secure method as it can run inside your application without permission hence more prone to th
3 min read
How to convert binary to decimal in JavaScript?
A binary number is a number expressed in the binary numeral system, which uses only two symbols 0 and 1. Decimal numbers are base 10 in a JavaScript number system that uses 10 digits from 0 to 9. We are given a number as Binary input we have to convert it into decimal in JavaScript and print the res
3 min read