JavaScript program to print the Fibonacci series.
In this article, we are going to learn about the Fibonacci Sequence. We will discuss the logic and the code. There will be two different codes. The first is for up to n terms and the second one is for up to a certain number. To understand the code you should have knowledge about arrow functions and basic JavaScript. You can find the tutorial link below.
- Learn more about Arrow Functions in JavaScript
- Learn basic JavaScript Syntax.
Let’s continue…
The Fibonacci sequence/series is a set of numbers that starts with a one (1) or a zero (0), followed by a one, and proceeds based on the rule that each number is equal to the sum of the preceding two numbers. If the Fibonacci sequence is denoted F (n), where n is the first term in the sequence, the following equation obtains for n = 0, where the first two terms are defined as 0 and 1 by convention:
F(0) = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
or if you have given n = 1 the Fibonacci series will be
F(1) = 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Fibonacci Series upto n terms
// program to generate fibonacci series up to n terms
// function is taking a parameter to print upto number.
const fibonacci = terms => {
let num1 = 0; // starting number of the series
let num2 = 1; // second number of the series
let nextNum; // stores the next number
let series = ''; // stores the series in string format
for(let i = 1; i <= terms; i++){
series += num1 + ' '; // appending the number into the string
nextNum = num1 + num2;
num1 = num2;
num2 = nextNum;
}
return series; // returns the series of the fibonacci
}
console.log("Fibonacci Series of 7 Numbers is: " + fibonacci(7));
Output
Fibonacci Series of 7 Numbers is: 0 1 1 2 3 5 8
In the above program, the function gets the number to iterate in the Fibonacci series. The for loop iterates up to the number(terms) entered by the user.
0 is printed at first. Then, in each iteration, the value of the second term is stored in variable num1 and the sum of two previous terms is stored in variable num2.
Fibonacci Series up to a Certain Number
// program to generate Fibonacci series up to a certain number
const fibonacci = num => {
let num1 = 0, num2 = 1, nextNumber;
let series = ''; // this will store the string of fibonacci series
series = num1 + ' ' + num2 + ' '; // appending first two values of the series
nextNumber = num1 + num2; // next term will be num1 + num2
while (nextNumber <= num) {
series += nextNumber + ' ';
num1 = num2;
num2 = nextNumber;
nextNumber = num1 + num2;
}
return series;
}
console.log("Fibonacci Series of Number 7 is: " + fibonacci(7));
Output
Fibonacci Series of Number 7 is: 0 1 1 2 3 5
In the above example, the function will get the number that the user wants to print the Fibonacci series.
The first two terms 0 and 1 are displayed. Then, a while loop will iterate to find the Fibonacci series up to the number.