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 calculate minutes between two dates in JavaScript ?
Given two dates and the task is to get the number of minutes between them using JavaScript. Approach: Initialize both Date object.Subtract the older date from the new date. It will give the number of milliseconds from 1 January 1970.Convert milliseconds to minutes. Example 1: This example uses the c
2 min read
How to create a function from a string in JavaScript ?
The task is to create a function from the string given in the format of the function. Here are a few approaches that are listed below: Using Function() ConstructorUsing eval() MethodApproach 1: Using Function() ConstructorUse the Function() Constructor to create a function from the string.It accepts
2 min read
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 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 iterate over a callback n times in JavaScript?
Given a callback function, we have to iterate over a callback n times. The callback is a function that is passed as an argument. To iterate over the callback function, we have to run the callback function n time. Here we have some common approaches: Table of Content Using recursion to iterate the n
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. Syntax arr.reduce( callback( acc,
2 min read
How to Parse Float with Two Decimal Places in JavaScript?
JavaScript provides an inbuilt parseFloat() method to parse a string and returns a floating-point number. Below are the approaches to parse float to two decimal places in JavaScript: Table of Content Using parseFloat() MethodUsing Custom parseFloat Method Approach 1: Using parseFloat() MethodThe par
2 min read
nth Multiple of a Number in Fibonacci Series in JavaScript
The Fibonacci series is a sequence of numbers where each number is the sum of the two previous ones, usually starting with 0 and 1. Given two integers n and k, the task is to find the position of the nth multiple of k in the Fibonacci series. For instance, if k = 2 and n = 3, the output would be 9 s
4 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 = 1 Examples: Input :
4 min read