how to create fibonacci in javascript

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. In Javascript, we can create a function that generates the Fibonacci sequence using recursion.

index.tsx
function fibonacci(num) {
  if (num <= 1) return 1;

  return fibonacci(num - 1) + fibonacci(num - 2);
}

console.log(fibonacci(5)); // returns 8
console.log(fibonacci(10)); // returns 89
188 chars
9 lines

In the code above, we declare a function called fibonacci that takes a single argument num. If the argument is less than or equal to 1, we return 1 since 0 and 1 are the first two numbers in the Fibonacci sequence. Otherwise, we return the sum of the two previous numbers in the sequence using recursion.

We can test the function by calling it with different arguments and logging the results in the console. When we call fibonacci(5), the function calculates the 5th number in the sequence, which is 8. Similarly, when we call fibonacci(10), the function calculates the 10th number in the sequence, which is 89.

gistlibby LogSnag