# Fibonacci numbers (JavaScript)

**Other implementations**: bc | C | C Plus Plus templates | dc | E | Forth | FORTRAN | Haskell | Icon | Java |**JavaScript**| Lisp | Lua | occam | Oz | PIR | Prolog | Python | Sed | sh | sh, iterative | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.

## Contents |

## [edit] Implementation

The [fibonacci] numbers in JavaScript:

<<fib.js>>=fib fastfib testdriver

## [edit] Recursive

This is a very simple recursive implementation. This will become slow on big numbers, because the numbers are recalculated for each recursion.

<<fib>>=function fib(n){returnn<2?n:fib(n-1)+fib(n-2);}

## [edit] Iteration

Although it is based directly on the definition of a Fibonacci number, the recursive Fibonacci algorithm is extremely expensive, requiring time *O*(2^{n}). It also performs a huge amount of redundant work because it computes many Fibonnaci values from scratch many times. A simple linear-time iterative approach which calculates each value of fib successively can avoid these issues. The result from the 2 last calculations are stored in a dynamic array, to avoid all the recalculations in the recursive implementation.

<<fastfib>>=function fastfib(n){vari;varfibs =newArray();

We start by `push`

ing the first two values into the array, which is initially empty.

<<fastfib>>=fibs.push(0); fibs.push(1);

The heart of the function is a for-loop. In each iteration of the loop we first `push`

the sum of the current values of the array onto the end of the array, and then `shift`

the array to remove the first element of the array. Thus, the first iteration will proceed like this:

fibsinitially [0,1] fibs.push(fibs[0] + fibs[1]);fibsnow [0,1,1] fibs.shift();fibsnow [1,1]

The actual implementation is

<<fastfib>>=for(i=0; i<n; i++){fibs.push(fibs[0] + fibs[1]); fibs.shift();}returnfibs[0];}

## [edit] Test driver

<<testdriver>>=for(i=0; i<=20; i++)document.write("fib(" + i + ") = " + fib(i) + "<br/>");for(i=0; i<=20; i++)document.write("fastfib(" + i + ") = " + fastfib(i) + "<br/>");

Download code |