Fibonacci Sequence program in JavaScript

In the Fibonacci sequence is a series, next number is the addition of the last two numbers, the Fibonacci series starts with 0, and 1.

Fibonacci Series in JavaScript using for loop

In this program, the user will take a length of the series through prompt and find Fibonacci Sequence by using for loop.

<!DOCTYPE html>
<html>
<body>
    <script>
        function fibonacci()
        {
          var a=0,b=1,fib=0,n,i;
          var n=prompt("Enter the length of series:");
          document.write(a+"</br> "+b+"</br>");
          for(i=2;i<n;i++)
          {
            fib=a+b;
            document.write(fib+"</br>");
            a=b;
            b=fib;
          }
        }
    </script>
    <form>
        <input type="button" value="fibonacci" onclick="fibonacci();">
    </form>
 </body>
</html>
 
Run now

Input has taken through javascript prompt method

output

Enter the length of series:9
0
1
1
2
3
5
8
13
21

Logic to print Fibonacci series for a given length:

  • Take a length of series as an input from the user using a javascript prompt and store it in a variable n.
  • Fibonacci series starts with 0 and 1, so print 0 and 1 at the beginning which is stored in variables a and b.
  • For finding the next term add the previous two-term inside for loop i.e fib=a+b.
  • print the current Fibonacci series number i.e fib and for finding the next Fibonacci series number, copy the value of b into a, i.e a=b, and copy the fib value to b, i.e, b=fib inside for loop.

Program to print Fibonacci Series in JavaScript using while loop

In this program, the user will take a length of the series through prompt and find Fibonacci Sequence by using while loop.

<!DOCTYPE html>
<html>
<body>
    <script>
        function fibonacci()
        {
          var a=0,b=1,fib=0,n,i;
          var n=prompt("Enter the length of series:");
          document.write(a+"</br> "+b+"</br>");
	  i=2;
          while(i<n)
          {
            fib=a+b;
            document.write(fib+"</br>");
            a=b;
            b=fib;
	    i++;
          }
        }
    </script>
    <form>
        <input type="button" value="fibonacci" title="fibonacci series" onclick="fibonacci();">
	</form>
</body>
</html>            
 

Input has taken through javascript prompt method

output

Enter the length of series:10
0
1
1
2
3
5
8
13
21
34