javascript fibonacci numbers code example
Example 1: js fibonacci sequence
function fibonacci(nums) {
let fib = [0, 1];
let data = [];
for(let i = 2; i <= nums; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
data.push(fib[i]);
}
return data;
}
Example 2: javascript fibonacci
function fibonacci(n) {
return n < 1 ? 0
: n <= 2 ? 1
: fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(4));
Example 3: js fibonacci sequence
var i;
var fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
console.log(fib[i]);
}
Example 4: javascript fibonacci
const number = parseInt(prompt('Enter the number of terms: '));
let n1 = 0, n2 = 1, nextTerm;
console.log('Fibonacci Series:');
for (let i = 1; i <= number; i++) {
console.log(n1);
nextTerm = n1 + n2;
n1 = n2;
n2 = nextTerm;
}