write a javascript function fibonacci sequence() to generate a fibonacci sequence code example
Example 1: how to generate a fibonacci sequence in javascript
// declare the array starting with the first 2 values of the fibonacci sequence
let fibonacci = [0,1];
function listFibonacci(num) {
// starting at array index 1, and push current index + previous index to the array
for (let i = 1; i < num; i++) {
fibonacci.push(fibonacci[i] + fibonacci[i - 1]);
}
console.log(fibonacci);
}
listFibonacci(10);
Example 2: js fibonacci sequence
var i;
var fib = []; // Initialize array!
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
// Next fibonacci number = previous + one before previous
// Translated to JavaScript:
fib[i] = fib[i - 2] + fib[i - 1];
console.log(fib[i]);
}