In this article, knowledge will be provided on how anyone can implement this concept into JavaScript code.
Creating Fibonacci Series in JavaScript
Like many other programs in JavaScript, this one also utilizes a few different variables and a for loop. To break down the code into a simple program, it has been divided into 2 sections. Check out the different sections below.
Section 1: Declaring Variables
The first section is the simplest one. In this section, some variables are declared. Let’s explain the work behind these variables. The num variable is the maximum limit of the Fibonacci series. The firstNum will initially hold the first value of the series. Then inside the program, it holds the first number that has to be added to the second number which is the secondNum variable. Take a look at the code below:
var num=4, firstNum = 0, secondNum = 1;
var next;
Section 2: Using Loop to print values
This is the main section where the Fibonacci Series is made and displayed. It starts with a for loop between the range of 0 and num. The first step in this section is to display the firstNum value which in this case is zero initially. Then the variable sum is temporarily assigned the value of the firstNum added into the secondNum. The next step is to move the firstNum forward in the series. This is accomplished by assigning the value of secondNum to firstNum. Afterward, secondNum is given the sum value which moves secondNum forward in the series.
for ( var i = 0; i < num; i++)
{
document.write("<br>" + firstNum);
sum = firstNum + secondNum;
firstNum = secondNum;
secondNum = sum;
}
The loop is then repeated with new values of firstNum and secondNum and this way the entire series is printed this way. Below is an example of how this code will run with the value of num being 8:
This is the easiest way to implement the Fibonacci Series in JavaScript. If someone desires they can take user input instead of hard coding the maximum number in the series.
Conclusion
You can get the Fibonacci series using JavaScript by using for loop to implement 3 crucial variables. The firstNum variable holds the first value and secondNum holds the second value. The sum variable calculates its sum and moves the series forward by assigning the sum value to secondNum. In this article, every variable is explained in depth and how they all work together to display the Fibonacci Series.