Dummy - 1 year ago 47

Javascript Question

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`

`2`

`/*`

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

`<button>Click me</button>`