Find the Nth Number of Fibonacci series using JavaScript

Here’s some fun finding the Nth number of a Fibonacci series using JavaScript Recursion

<html xmlns="" >
<title>Nth Fibonacci Series</title>
<script type="text/javascript">
function callFibo() {
//extract textbox value
var num = document.getElementById('txtFibo').value;
//check if it is a number and greater than 1 and less than 36
if (isNaN(num) ((num < 1) (num > 35))) {
alert("Only numbers allowed. Enter a number > 0 and < 35");
else {
alert("Number " + num + " in the Fibonacci series is " +

function calcFiboNth(num) {
if (num > 2) {
return calcFiboNth(num - 2) + calcFiboNth(num - 1);
} else {
return 1;

<input id="txtFibo" type="text" />
<br /><br />
<input id="btnFibo" type="button" value="Enter a Number and click"
onClick="callFibo()" />

The function calcFiboNth() makes a recursive call to itself each time with a different ‘num’ value and this continues till ‘num’ reaches 1. That’s how you get the Nth number of the series.

Note: It is a good idea to add an upper limit to the number entered. Entering a higher number could take a very long time to compute the nth number of the Fibonacci series.


See a Live Demo

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: