Generating Fibonacci Series using JavaScript


Today lets see how to generate Fibonacci Series using JavaScript programming.

First Thing First: What Is Fibonacci Series ?
Fibonacci Series is a series of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Its recurrence relation is given by Fn = Fn-1 + Fn-2.

Below are a series of Fibonacci numbers(10 numbers):
0
1
1
2
3
5
8
13
21
34

How Its Formed:
0 <– First Number
1 <– Second Number
1 <– = 1 + 0
2 <– = 1 + 1
3 <– = 2 + 1
5 <– = 3 + 2
8 <– = 5 + 3
13 <– = 8 + 5
21 <– = 13 + 8
34 <– = 21 + 13

Video Explaining The JavaScript Code To Generate Fibonacci Series:



YouTube Link: https://www.youtube.com/watch?v=V8WwUwOxm5M [Watch the Video In Full Screen.]


Some points to keep in mind:
1. In Javascript, it is not mandatory to declare a variable before using it. But still its a good practice to declare it before using.
2. Using html comments inside javascript code ensures that, the old browsers which do not support javascript will ignore all the code written inside the script tags.
3. If we give a very large number while entering the limit, then the loop start executing and the browser memory will soon exhaust and the browser may stop responding.
4. You can use any valid html coding inside document.write statement, as the output will be then processed by a html browser.

JavaScript Code Shown In Above Video:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 <title>Fibonacci Series</title>
 
<script type="text/javascript">
<!--
 
var var1 = 0;
var var2 = 1;
var var3;
 
var num = prompt("Enter the limit to generate fibonacci no",0);
 
document.write(var1+"<br />");
document.write(var2+"<br />");
 
for(var i=3; i < = num;i++)
{
var3 = var1 + var2;
var1 = var2;
var2 = var3;
 
document.write(var3+"<br />");
}
 
// -->
</script>

In JavaScript:
Variable declaration is done using var keyword, followed by the variable name.
document.write is the output statement.
prompt is used to get the input from the user.

Even though the above program is easy, you may forget the logic when it is needed. So don’t forget to actually pullout a text editor and try it out yourself.

12 thoughts on “Generating Fibonacci Series using JavaScript”

  1. Here is little modified function of the Fibonachi number, with call of the function to the eight element

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
    function fibonachi(nElement) {
     
    var arr = new Array();
    //alert(arr);
    for (var i=0;i&lt;=nElement;i++) { 
    if (i == 0) {
    arr[0] = i;
    continue;
    }
    if (i == 1){
    arr[i] = i;
    continue;
    }
    arr[i] = arr[i-1] + arr[i-2];
    }
    alert(arr);
    }
    fibonachi(8);

Leave a Reply

Your email address will not be published. Required fields are marked *