recursion fibonacci javascript code example
Example 1: javascript recursive fibonacci
function recursiveFibonacci(n){
if(n === 0) return 0
if(n === 1) return 1
return recursiveFibonacci(n - 2) + recursiveFibonacci(n - 1);
}
recursiveFibonacci(6)
function iterativeFibonacci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let previous = 0;
let current = 1;
for (let i = n; i > 1; i--) {
let next = previous + current;
previous = current;
current = next;
}
return current;
}
iterativeFibonacci(6)
Example 2: javascript fibonacci example
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 3: fibonacci best performance javascript
function fibonacci(n) {
const list = [0, 1];
for (let x = 2; x < n + 1; x += 1) {
list.push(list[x - 2] + list[x - 1]);
}
return list[n];
}
console.log(fibonacci(4));
Example 4: recursive function for fibonacci series in java javascript
var fib = function(n) {
if (n === 1) {
return [0, 1];
} else {
var arr = fib(n - 1);
arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
return arr;
}
};
console.log(fib(8));
Example 5: recursive function for fibonacci series in java javascript
var fib = function(n) {
if (n === 1) {
return [0, 1];
} else {
var arr = fib(n - 1);
arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
return arr;
}
};
console.log(fib(2));
Example 6: javascript recursive function for fibonacci series
Enter the number of terms: 12
0
1
1
2
3