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

function Fibonacci(valor){
	var anterior = 0;
	var atual = 1;
	var proximo = 1;

	for(let i = 0; i < valor; i++){
		console.log(proximo)
		anterior = atual + proximo;
		atual = proximo
		proximo = anterior
	}
}

Fibonacci(100);

Example 5: javascript fibonacci example

// number fibonnaci to array format
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 6: 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]);
    }