Generate a Fibonacci sequence

Posted on  • tagged with #javascript

The Fibonacci sequence is a series of numbers where each number in the sequence is the sum of the two preceding numbers. This sequence begins with 0 and 1. In mathematics, the Fibonacci numbers form the sequence, where numbers (n) are greater than 1 (n > 1).

To better understand how the fibonacci numbers are created in the sequence, view the below equation for generating any number in the fibonacci sequence.

Fn = Fn-1 + Fn-2

Generate the sequence

Now that the underlying mathematical equation for generating the Fibonacci sequence is known, let's write a JavaScript function to create it.

function fibonacciSeq(n) {
let sequence = [0, 1];
for (var i = 1; i < n; i++) {
let num = arr[i] + arr[i-1];
sequence.push(num);
}
return num;
}

The above function fibonacciSeq accepts one parameter, the amount of fibonacci numbers to generate in the sequence and returns an array containing the fibonacci sequence. For example, passing in n = 7 will generate the following sequence:

console.log(fibonacciSeq(7));
// [0, 1, 1, 2, 3, 5, 8, 13]