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.tsx188 chars9 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