0

I've been trying to solve the Fibonacci sequence and tried it with the following approach:

function fibbi(number) {
    for (let number = 0; number < 10; number++) {
        console.log(fibbi(number));
    }if (number < 2) {
        return number;
    } else {
        return fibbi(number - 1) + fibbi(number - 2);
    }
}
fibbi(10);

Through that, I'm running into an infinite loop and I don't really understand why. Could someone walk me through this maybe? If I put the for loop outside of the function and call the function there, it will not run into an infinite loop.

Edit: Changed function name in else statement

Sam
  • 41
  • 3
  • 2
    What have you tried to resolve the problem? Where are you stuck? Looks like you call `fibbi` recursively without any condition that stops this – Nico Haase Aug 04 '22 at 13:55
  • ...which you do in line #3 – skyboyer Aug 04 '22 at 13:56
  • Your function is named `fibbi` but your last return statement is attempting to call a function named `fibonacci` – skyline3000 Aug 04 '22 at 13:56
  • Does this answer your question? [How to implement a Fibonacci sequence in JavaScript?](https://stackoverflow.com/questions/70384233/how-to-implement-a-fibonacci-sequence-in-javascript) – jsejcksn Aug 04 '22 at 13:57
  • Why is that loop in your `fibbi` function to begin with? I don't think it is supposed to be there. Move it out of the function, use consistent names and your function should work fine. – Ivar Aug 04 '22 at 14:00
  • Is there a way to write this without the loop? – Sam Aug 04 '22 at 14:07
  • @Sam Why don't you just remove it? It doesn't belong there. – Ivar Aug 04 '22 at 14:16

1 Answers1

1

You have done something with isn't clear. Why you have made function called fibbi 10 times within the loop? Seems like you are solving this using recursion approach.

Let's understand how to solve a Fibonacci sequence. There are many approach to solve. Let's discuss using recursion.

function fib(n) {
    if (n <= 1)
        return n;
    return fib(n-1) + fib(n-2);
}

                          fib(5)   
                     /                \
               fib(4)                fib(3)   
             /        \              /       \ 
         fib(3)      fib(2)         fib(2)   fib(1)
        /    \       /    \        /      \
  fib(2)   fib(1)  fib(1) fib(0) fib(1) fib(0)
  /     \
fib(1) fib(0)

So let's say you made a function call fib(5). You are telling the computer. Hey can you find the 4th fibonacci number and return me so I will later find 3rd Fibonacci number and add it so I can have the Required result. Now again fib(4) will tell hey can you find 3rd Fibonacci number so I will later find 2nd Fibonacci number and add it so I can have 4th fibonacci number and return it to previous call and so on. Similarly for right hand side of tree. this is how the call works. Hope it helped.

Mulan
  • 129,518
  • 31
  • 228
  • 259