Home >>Javascript Programs >Print a fibonacci series in JavaScript

Print a fibonacci series in JavaScript

How to Print Fibonacci Series in Javascript

In this tutorial we will learn what is Fibonacci series and how to print Fibonacci series in javascript.

Fibonacci series defined the sequences of a number in recurrence relation. It generates a subsequent number by adding second and third term preceding number and not using the first term. It can be done as requested by the user until the number of terms.

In case of Fibonacci series like 0, 1, 1, 2, 3, 5, 8, 13, 21 etc.

Let's take an example:

		<title>Fibonacci series in JavaScript</title>
			function getFibonacci()
			var limit = document.getElementById("limit").value;
			function fibonacciSeries(limit)
				var first_num = 0, second_num = 1, next_num, outputElement;

				if(limit != '')
					outputElement = document.getElementById("output"); 
					outputElement.innerHTML = "";
					outputElement.innerHTML = "<br>";
					outputElement.innerHTML += first_num + "<br>";
					outputElement.innerHTML += second_num + "<br>";
					while(limit > 2)
					   next_num   = first_num + second_num;
					   first_num  = second_num;
					   second_num = next_num;
					   outputElement.innerHTML += next_num + "<br>";
					document.getElementById("output").innerHTML = "Please enter a value!";
		<h2>Fibonacci series</h2>
		<h3>Enter the limit:</h3>
		<input type="text" id="limit" />
		<button onclick="getFibonacci()" >Print Fibonacci Series</button>
        <h4>Output: <span id="output"></span></h4>

Fibonacci series

Enter the limit: