Fibonacci on Nature

Fibonacci JavaScript Function to Print the Sequence

v
Name is the most famous version in the series of publisher
Publisher
Genre Javascript
Version
Update August 15, 2023
Report Report Apps
Download

Here is a JavaScript function that generates the Fibonacci sequence up to a certain number of terms:

function fibonacci(n) {
  let a = 0, b = 1;
  let fib = [a, b];
    for (let i = 2; i < n; i++) {
      let c = a + b;
      fib.push(c);
      a = b;
      b = c;
    }
  return fib;
}

To use this function, you would call it and pass in the desired number of terms as an argument, like this:

let sequence = fibonacci(10); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

This function works by using a for loop to iterate over the desired number of terms. The loop begins by defining two variables, a and b, which are initialized to 0 and 1, respectively. These two variables represent the first two terms in the Fibonacci sequence. The loop also initializes an array, fib, which will be used to store the generated sequence.

In each iteration of the loop, the next term in the sequence is calculated by adding a and b together. This new term is then added to the fib array, and the values of a and b are updated to be the previous two terms in the sequence. This process continues until the desired number of terms has been generated, at which point the fib array is returned.

Report

Recommended for You

You may also like