Computer >> Computer tutorials >  >> Programming >> Javascript

Nth element of the Fibonacci series JavaScript


We are required to write a JavaScript function that takes in a single number as the first and the only argument, let’s call that number n.

The function should return the nth element of the Fibonacci series.

For example −

fibonacci(10) should return 55
fibonacci(3) should return 2
fibonacci(6) should return 8
fibonacci(2) should return 1

Example

const fibonacci = (num = 1) => {
   const series = [1, 1];
   for (let i = 2; i < num; i++) {
      const a = series[i - 1];
      const b = series[i - 2];
      series.push(a + b);
   };
   return series[num - 1];
};
console.log(fibonacci(10));
console.log(fibonacci(6));
console.log(fibonacci(3));
console.log(fibonacci(2));

Output

And the output in the console will be −

55
8
2
1