Fibonacci series in JavaScript

In this article, we will explore the Fibonacci sequence and examine methods to generate the Fibonacci series using JavaScript.

The Fibonacci sequence is a mathematical series that produces new numbers by summing the two preceding numbers. The initial two terms of this sequence are zero and one. Following these, each subsequent term is obtained by adding the two most recent terms.

Representation of the Fibonacci series

Example

Fn = (Fn -1) + (Fn - 2)

Fn signifies the sum of the preceding terms, specifically (Fn - 1) and (Fn - 2). In this context, Fn-1 represents the first term, while Fn-2 denotes the second term within the Fibonacci sequence.

Example:

  • First term of the series is 0
  • Second term of the series is 1
  • Third term of the series is (0 + 1) = 1
  • Fourth term of the series is (second + third) term = (1 + 1) = 2
  • Fifth term of the series is (third + fourth) = 1 + 2 = 3

Presented below is a generated sequence: 0, 1, 1, 2, 3, and continues in this manner. In the same way, we can determine the subsequent terms of the series.

Steps to generate the Fibonacci series of n numbers

Here are the steps to determine the Fibonacci Series:

Step 1: Declare the variables x, y, z, n, and i.

The variables x and y will hold the initial two values, z will represent the subsequent term, n will denote the total count, and i will function as the counter for the loop.

Step 2: Initialize the local variable:

  • x = 0 (First Fibonacci Number)
  • y = 1 (Second Fibonacci Number)
  • i = 2 (Since the first two numbers are already known)

Step 3: Read the value of n from the user.

Step 4: Show the values of x and y.

Step 5: Repeat the procedure of Fibonacci series until i > n.

  • z = x + y
  • Display the value of z
  • x = y, y = z
  • i = i + 1

Step 6: Terminate the execution of the Fibonacci sequence.

Get the Fibonacci series up to n terms

Let’s examine an instance of generating the Fibonacci sequence up to a specified value in JavaScript by employing a for loop.

Code:

Example

Example

<html>

<head>

<title> Fibonacci Series in JavaScript </title>

</head>

<body>

<script>

// declaration of the variables

var n1 = 0,  n2 = 1, next_num, i;

var num = parseInt (prompt (" Enter the limit for Fibonacci Series "));

document.write( "Fibonacci Series: ");

for ( i = 1; i <= num; i++)

{  document.write (" <br> " +  n1); // print the n1

	next_num = n1 + n2; // sum of n1 and n2 into the next_num

	

	n1 = n2; // assign the n2 value into n2

	n2 = next_num; // assign the next_num into n2

}



</script>

</body>

</html>

Output:

Upon running the aforementioned program, it presents the specified output. A prompt box appears, allowing users to set the limits for the Fibonacci series. Here, you can input your desired limit and proceed by clicking the OK button to move forward.

Upon inputting a limit of 11 for the Fibonacci Series and subsequently clicking the OK button.

It presents the Fibonacci sequence, commencing with the values 0 and 1. Each subsequent term in the series is derived from the sum of the two preceding terms, as illustrated below.

Fetching the Fibonacci series of the first 8 terms

Let’s examine an example that generates the Fibonacci sequence for the initial 8 terms using JavaScript with the implementation of for loops and if-else conditions.

Code:

Example

Example

<html>

<head>

<title>

Fibonacci Series in JavaScript </title>

</head>

<body>

<script type = "text/javascript">

// declaration of the variables

var number = 8; 

var num1 = 0, num2 = 1;

var next_term = 0;

document.write( " Fibonacci series of the number 8: " + "<br>")

for (i = 1; i < number; i++) // use for loop to iterate the series till given number 

{

if ( i <= 1) 

next_term = i; // assign the variable i to next_term

else

{

next_term = num1 + num2; // sum the num1 and num2

num1 = num2;

num2 = next_term;

}

// print the sum of the series

document.write( " Adding " + num1 + " and " + next_term + " = " + (num1 + num2) + "<br>" );



}

</script>

</body>

<html>

Output:

Get the sum of the first 7 terms of the Fibonacci series

Let us examine an example that demonstrates how to calculate the sum of the Fibonacci sequence in JavaScript by utilizing a function in conjunction with a for loop.

Code:

Example

Example

<html>  

<head>  

<title>  

Fibonacci Series in JavaScript </title>  

</head>  

<body>  

<script type = "text/javascript">  

function fibo( num)  

{  

var n1 = 0; // declaration of variables n1, n2, i and temp.  

var n2 = 1;  

var temp;  

var i = 0;  

for (i = 0; i < num; i++)  

{  

temp = n1 + n2; // store the sum of n1 and n2 in temp variable.  

n1 = n2; // assign the n2 value into the n1 variable  

n2 = temp; // assign the new value of temp into n2 variable  

}  

return n2;  

}  

// get a number from the user  

const f1 = parseFloat (prompt (' Enter a number to get the sum of Fibonacci Series '));  

window.alert( "The sum of Fibonacci Series is " +fibo(f1) );  /* print the sum of series */  

  

</script>  

</body>  

</html>

Output:

Upon executing the code mentioned above, a prompt box appears, requesting a numerical input to calculate and return the sum of the Fibonacci series.

In this instance, we have provided 7 as the input in order to obtain the sum of the series, as illustrated below.

Upon clicking the OK button, the result displayed is the total of the initial 7 terms, equating to 21.

Get the Fibonacci series using Recursion Function

Let's examine an illustration of generating the Fibonacci series in JavaScript by utilizing a recursive function.

Code:

Example

Example

<html>  

<head>   

<title>   

Fibonacci Series using Recursion in JavaScript. </title>  

</head>  

<body style= "text-align: center;">  

<h2> Fibonacci Series in JavaScript Using Recursion </h2>  

  

<script>  

// Using Recursion to find the Fibonacci Series.  

function recur(num)  

{  

// when num is equal to 1, it returns 0 and 1  

if (num == 1)  

{  

return [0, 1];  

}  

else  

{  

// it continuously calls the recur function till n-1  

total = recur (num - 1);  

/* push function adds previous two terms and stores the result into the total variable. */   

total.push( total[ total.length - 1] + total[ total.length - 2]);  

return total;  

}  

  

}  

// Series of first 12 terms using Recursion.  

document.write("Fibonacci Series of f(12) in JavaScript: " + recur( 12 ) + "<br>");  

</script>  

</body>  

</html>

Output:

In the program outlined above, the Fibonacci sequence is generated through a recursive function that does not rely on traditional looping constructs. The function recur invokes itself repeatedly, decrementing the num parameter by 1 with each invocation until it arrives at the base case recur(1), which returns the initial values [0, 1].

Upon concluding each recursive call, the subsequent Fibonacci number is determined by summing the two most recent numbers in the sequence. This new number is then added to the series using the push method. Ultimately, the entire sequence is returned and displayed on the web page.

Get the Fibonacci series in Reverse Order

Let's examine an instance of generating the Fibonacci series in reverse order utilizing a for loop.

Code:

Example

Example

<html>

<head>

<title>

Reverse Fibonacci Series

</title>

</head>

<body style= "text-align: center;">

<h2> Fibonacci Series in Reverse Order </h2>

<script>

var a = 1, b = 0, res, num;

num = prompt( "Enter the number of terms ");

document.write ("Fibonacci Series of " + num + " terms  is " );

for ( var i =0; i < num; i++)

{

document.write ("  " + b);

res = a + b;

a = b;

b = res;

}

document.write( "" + "<br>");

document.write( "Fibonacci Series of " + num + " terms in Reverse Order is " + "<br>"); 

// print the series in reverse order

for ( i = 0; i < num; i++)

{

document.write( "  " +  a);

res = b - a;

b = a;

a = res;

}

</script>

</body>

</html>

Output

Upon executing the code provided above, a prompt dialog appears to request a numerical input from the user.

In this scenario, we have input the value of 10 and subsequently pressed the OK button. Following this action, the system produces the Fibonacci sequence for the initial 10 terms, displaying them first in ascending order and then in reverse order.

Frequently Asked Questions (FAQs)

  1. What exactly is the Fibonacci Sequence in JavaScript?

The Fibonacci Series is a numerical sequence that initiates with the values 0 and 1, wherein each subsequent number is derived from the sum of the two preceding numbers. This sequence continues indefinitely. It can be expressed as 0, 1, 1, 2, 3, 5, and so forth.

  1. What is the importance of comprehending the Fibonacci Series in JavaScript?

The Fibonacci Series serves as an excellent foundation for novices to grasp fundamental programming principles such as recursion, loops, and array handling. It provides a practical approach to gain hands-on experience with logical reasoning and coding syntax in JavaScript.

  1. Which approach is superior for generating the Fibonacci sequence in JavaScript: iterative or recursive?

Both iteration and recursion come with their distinct benefits and drawbacks. Generally, iteration tends to be more structured and quicker, particularly when dealing with large sequences. On the other hand, recursion in JavaScript offers a more elegant and intuitive approach than iteration; however, it may prove to be less efficient and consume more memory when managing extensive sequences.

  1. Provide examples of practical uses for the Fibonacci Series.

The Fibonacci Series finds its application in a variety of real-life scenarios. It plays a significant role in financial forecasting, enhancing algorithm efficiency, and is also employed in the examination of biological structures and occurrences.

  1. Is it possible to use JavaScript to display the Fibonacci Series on a web page?

Indeed, JavaScript can be employed to generate and display the Fibonacci Series on a web page. We can leverage document manipulation techniques to construct and insert elements into the HTML to present the series effectively.

  1. What is the commonly used algorithm for generating the Fibonacci series in JavaScript?

Typically, programmers employ either a for loop or a while loop to generate the Fibonacci sequence.

  1. What is the functioning of the Fibonacci Series in JavaScript?

The Fibonacci sequence is a mathematical series in JavaScript that starts with the initial values of 0 and 1. Each subsequent number in the series is generated by summing the two preceding numbers.

  1. What is the number of variables required to compute the Fibonacci series?

Typically, a developer is required to define three variables. The first two variables are employed to store the initial two numbers in the sequence, while a third variable is used to hold the sum of these two preceding numbers.

Input Required

This code uses input(). Please provide values below: