recursive fibonacci js code example

Example 1: fibonacci javascript

function Fibonacci(num){
	var before = 0;
	var actual = 1;
	var next = 1;

	for(let i = 0; i < num; i++){
		console.log(next)
		before = actual + next;
		actual = next
		next = before
	}
}

Fibonacci(100);

Example 2: javascript recursive fibonacci

// Recursion way to return Fibonacci numbers
function recursiveFibonacci(n){
	// base case
	if(n === 0) return 0
  	if(n === 1) return 1
  
  	// recursioin base
  	return recursiveFibonacci(n - 2) + recursiveFibonacci(n - 1);
}
recursiveFibonacci(6) // should return 8

//////// and ////////

// Iteration way to return Fibonacci numbers
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) // should return 8

Example 3: javascript fibonacci

function fibonacci(n) {
   return n < 1 ? 0
        : n <= 2 ? 1
        : fibonacci(n - 1) + fibonacci(n - 2);
}

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: fibonacci sums javascript

// Implement a method that finds the sum of the first n
// fibonacci numbers recursively. Assume n > 0

function fibsSum(n) {
    if ( n === 1 ) {
        return 1;
    }
    if (n === 2 ) {
        return 2;
    }
    let sum = fibsSum(n-1) + n;
    return sum;
}