Dummy Dummy - 5 months ago 10
Javascript Question

Fibonacci Sequence Implementation Not Behaving As Expected

I want to print the first 5 numbers in the Fibonacci sequence starting with 1 and 2. I expect this code to print

1,2,3,5,8
when I execute the function, but somehow it only prints the last number which is 8 in this case. And if I execute the function many times after that, it always prints
2
. Why does it behave that way?



/*
Fibonacci sequence is calculated by the formula An = An-1 + An-2
@param prev An-2
@param next An-1
@param n the first n numbers to print
*/
var count = 0; // keeps track of which number we are on
function fibonacci(prev, next, n) {
// Need to subtract 2 or else it will print the first 7 numbers instead of 5
return count++ < n - 2 ? fibonacci(Math.max(prev,next), prev+next, n) + "," : next;
}

console.log(fibonacci(1, 2, 5));
console.log(fibonacci(1, 2, 5));
console.log(fibonacci(1, 2, 5));




Answer

You only use console.log with the last result. If you want to log all of them, you should use it inside the recursive function.

And the second time you click the button, it doesn't work because count is global. You could reset it to 0 inside the event listener, but better avoid globals.

function fibonacci(current, next, n) {
  if(n > 0) {
    console.log(current);
    fibonacci(next, current + next, n-1);
  }
}
document.querySelector('button').addEventListener('click', function() {
  fibonacci(1, 2, 5);
});
<button>Click me</button>