Nandakumar Edamana
Share on:
@ R t f

Fibonacci Numbers Using JavaScript


Printing the Fibonacci series has always been a classical example in programming language courses. It helps to illustrate some basic ideas like input, loops, buffering and output. This article shows you how to write a simple web page that includes the JavaScript code to generate the Fibonacci series.

The working is simple: user enters the number of elements he needs, presses a button, and gets the series. First let us have a look at the code and then have the explanation. We assume that you have a basic knowledge of HTML. However, we'll be discussing the JavaScript part in detail.

<!DOCTYPE HTML>
<html>
	<head>
		<title>Fibonacci Numbers Using JavaScript</title>
		<script>
			function on_btn_gen_click() {
				count = parseInt(document.getElementById("inCount").value);
				a = 0, b = 1, sum = 0;
				output = "<b>The first " + count + " elements in the Fibonacci series:</b> ";

				for(i = 0; i < count; i ++) {
					output += a + " ";
					sum = a + b;
					a = b;
					b = sum;
				}

				document.getElementById("pSeries").innerHTML = output;
			}
		</script>
	</head>
	<body>
		<h1>Fibonacci Numbers Using JavaScript</h1>
		Enter the count of terms: <input id="inCount" />
		<button id="btnGen" onclick="on_btn_gen_click()">Generate</button>
		<p id="pSeries" />
	</body>
</html>

Our page has some elements, among which three are crucial: a text input inCount, a button btnGen, an empty paragraph pSeries. Once the user enters the count of elements in the textbox and presses the button, the JavaScript function on_btn_gen_click is called (because the onclick attribute of the button has been set so).

Inside the function, the method document.getElementById(id) is used to select the elements from the HTML document. To mention about the content, .value is used in the case of input element and .innerHTML in the case of paragraph element (that's how the input and output works).

In short, document.getElementById("inCount").value means the value of the input element and document.getElementById("pSeries").innerHTML means the content of the [output] paragraph element.

Note that the function parseInt() is used with the input value in order to convert it from string to integer

Fibonacci series generation takes place inside the for loop, where each new elements is appended to the buffer string output. Finally, the string is assigned to the output paragraph element, and now the user gets the output.

And finally, see it in action:

Fibonacci Numbers Using JavaScript Enter the count of terms:


Keywords (click to browse): fibonacci-numbers fibonacci-series javascript js javascript-examples html web internet websites web-designing web-programming web-apps www