find the nth fibonacci number in javascript

index.tsx
function fibonacci(n) {
  if (n <= 1) {
    return n;
  } else {
    return fibonacci(n - 1) + fibonacci(n - 2);
  }
}

console.log(fibonacci(10)); // Output: 55
162 chars
10 lines

This is a recursive algorithm to find the nth fibonacci number in Javascript. The function takes in a number n and returns the nth fibonacci number. It uses recursion to calculate the fibonacci number by adding the previous two numbers in the sequence. The base case for the recursion is when n <= 1, in which case it returns n. Otherwise, it calls itself with n - 1 and n - 2 and returns the sum of the results.

In the example above, the function is called with n = 10, which returns the 10th fibonacci number, which is 55.

gistlibby LogSnag