1// Recursion way to return Fibonacci numbers
2function recursiveFibonacci(n){
3 // base case
4 if(n === 0) return 0
5 if(n === 1) return 1
6
7 // recursioin base
8 return recursiveFibonacci(n - 2) + recursiveFibonacci(n - 1);
9}
10recursiveFibonacci(6) // should return 8
11
12//////// and ////////
13
14// Iteration way to return Fibonacci numbers
15function iterativeFibonacci(n) {
16 if (n === 0) return 0;
17 if (n === 1) return 1;
18
19 let previous = 0;
20 let current = 1;
21 for (let i = n; i > 1; i--) {
22 let next = previous + current;
23 previous = current;
24 current = next;
25 }
26 return current;
27}
28
29iterativeFibonacci(6) // should return 8
30
31
1function fibonacci(n) {
2 if (n < 2){
3 return 1;
4 }else{
5 return fibonacci(n-2) + fibonacci(n-1);
6 }
7}
8
9console.log(fibonacci(7));
10//Returns 21
11
1var fib = function(n) {
2 if (n === 1) {
3 return [0, 1];
4 } else {
5 var arr = fib(n - 1);
6 arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
7 return arr;
8 }
9};
10
11console.log(fib(8));
1var fib = function(n) {
2 if (n === 1) {
3 return [0, 1];
4 } else {
5 var arr = fib(n - 1);
6 arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
7 return arr;
8 }
9};
10
11console.log(fib(2));