Dummy Dummy - 1 year ago 63
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

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
. 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 Source

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) {
    fibonacci(next, current + next, n-1);
document.querySelector('button').addEventListener('click', function() {
  fibonacci(1, 2, 5);
<button>Click me</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download