JavaScript Program to Find n-th Fibonacci Number
The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence goes as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Given an integer n, the task is to find the n-th Fibonacci number.
These are the following methods:
Table of Content
- Recursive Approach
- Iterative Approach
- Dynamic Programming Approach
Recursive Approach
In this method, the Fibonacci number is determined by a recursive function. Though straightforward, this method may be ineffective if repeated function calls are made.
Example: This example shows the recursive approach to find the nth term.
Javascript
function fibonacciRecursive(n) { if (n <= 1) return n; return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2); } const n = 12; console.log(`The ${n}-th Fibonacci number is : ${fibonacciRecursive(n)}`); |
The 12-th Fibonacci number is : 144
Iterative Approach
We compute the Fibonacci number sequentially using a loop. Due to the elimination of pointless function calls, it is more efficient than the recursive method.
Example: This example shows the Iterative approach to finding the nth term.
Javascript
function fibonacciIterative(n) { let fib = [0, 1]; for (let i = 2; i <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } return fib[n]; } const n = 12; console.log(`The ${n}-th Fibonacci number is: ${fibonacciIterative(n)}`); |
The 12-th Fibonacci number is: 144
Dynamic Programming Approach
We prevent unnecessary calculations by storing previously computed Fibonacci numbers in an array, which increases algorithmic performance.
Example: This example shows the Iterative approach to finding the nth term.
Javascript
function fibonacciDynamic(n) { let fib = [0, 1]; for (let i = 2; i <= n; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } return fib[n]; } const n = 2; console.log(`The ${n}-th Fibonacci number is: ${fibonacciDynamic(n)}`); |
The 2-th Fibonacci number is: 1
Conclusion
We have discussed three methods that you may use in JavaScript to find the n-th Fibonacci number. Iterative and dynamic programming methodologies are more efficient than the recursive approach, which is simpler but less effective.