JavaScript(JS) JS display fibonacci sequence using recursion

‮tfigi.www‬idea.com

Here's an example of how to display the Fibonacci sequence using recursion in JavaScript:

function fibonacci(num) {
  if (num <= 1) {
    return num;
  } else {
    return fibonacci(num - 1) + fibonacci(num - 2);
  }
}

function displayFibonacciSequence(count) {
  let sequence = [];
  for (let i = 0; i < count; i++) {
    sequence.push(fibonacci(i));
  }
  return sequence;
}

console.log(displayFibonacciSequence(10)); // Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

In the above example, we define a function called fibonacci that takes a number num as its argument. If num is 0 or 1, we simply return the value of num. Otherwise, we recursively call fibonacci with arguments of num - 1 and num - 2, and add the results together to get the nth Fibonacci number.

We then define a function called displayFibonacciSequence that takes a number count as its argument. We initialize an empty array called sequence and use a for loop to iterate count times. For each iteration, we call the fibonacci function with the current iteration number i and push the result to the sequence array.

Once the loop finishes, we return the sequence array, which contains the first count numbers of the Fibonacci sequence.

We then call the displayFibonacciSequence function with an argument of 10, which displays the first 10 numbers of the Fibonacci sequence and returns the array [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]. You can replace the value of the argument with any other number to display a different number of Fibonacci numbers.