You're defining a function in terms of itself. In general, fibonnaci(n) = fibonnaci(n - 2) + fibonnaci(n - 1). We're just representing this relationship in code. So, for fibonnaci(7) we can observe:

  • fibonacci(7) is equal to fibonacci(6) + fibonacci(5)
  • fibonacci(6) is equal to fibonacci(5) + fibonacci(4)
  • fibonacci(5) is equal to fibonacci(4) + fibonacci(3)
  • fibonacci(4) is equal to fibonacci(3) + fibonacci(2)
  • fibonacci(3) is equal to fibonacci(2) + fibonacci(1)
  • fibonacci(2) is equal to fibonacci(1) + fibonacci(0)
  • fibonacci(1) is equal to 1
  • fibonacci(0) is equal to 1

We now have all the parts needed to evaluate fibonacci(7), which was our original goal. Notice that the base case -- return 1 when n < 2 -- is what makes this possible. This is what stops the recursion, so that we can can start the process of unrolling the stack and summing the values we're returning at each step. Without this step, we'd continue calling fibonacci on smaller and smaller values right up until the program finally crashed.

It might help to add some logging statements that illustrate this:

function fibonacci(n, c) {
    var indent = "";
    for (var i = 0; i < c; i++) {
        indent += " ";
    }
    console.log(indent + "fibonacci(" + n + ")");
    if (n < 2) {
        return 1;
    } else {
        return fibonacci(n - 2, c + 4) + fibonacci(n - 1, c + 4);
    }
}

console.log(fibonacci(7, 0));

Output:

fibonacci(7)
    fibonacci(5)
        fibonacci(3)
            fibonacci(1)
            fibonacci(2)
                fibonacci(0)
                fibonacci(1)
        fibonacci(4)
            fibonacci(2)
                fibonacci(0)
                fibonacci(1)
            fibonacci(3)
                fibonacci(1)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
    fibonacci(6)
        fibonacci(4)
            fibonacci(2)
                fibonacci(0)
                fibonacci(1)
            fibonacci(3)
                fibonacci(1)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
        fibonacci(5)
            fibonacci(3)
                fibonacci(1)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
            fibonacci(4)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
                fibonacci(3)
                    fibonacci(1)
                    fibonacci(2)
                        fibonacci(0)
                        fibonacci(1)

Values at the same level of indentation are summed to produce the result for the previous level of indentation.

Answer from Wayne on Stack Overflow
Top answer
1 of 14
121

You're defining a function in terms of itself. In general, fibonnaci(n) = fibonnaci(n - 2) + fibonnaci(n - 1). We're just representing this relationship in code. So, for fibonnaci(7) we can observe:

  • fibonacci(7) is equal to fibonacci(6) + fibonacci(5)
  • fibonacci(6) is equal to fibonacci(5) + fibonacci(4)
  • fibonacci(5) is equal to fibonacci(4) + fibonacci(3)
  • fibonacci(4) is equal to fibonacci(3) + fibonacci(2)
  • fibonacci(3) is equal to fibonacci(2) + fibonacci(1)
  • fibonacci(2) is equal to fibonacci(1) + fibonacci(0)
  • fibonacci(1) is equal to 1
  • fibonacci(0) is equal to 1

We now have all the parts needed to evaluate fibonacci(7), which was our original goal. Notice that the base case -- return 1 when n < 2 -- is what makes this possible. This is what stops the recursion, so that we can can start the process of unrolling the stack and summing the values we're returning at each step. Without this step, we'd continue calling fibonacci on smaller and smaller values right up until the program finally crashed.

It might help to add some logging statements that illustrate this:

function fibonacci(n, c) {
    var indent = "";
    for (var i = 0; i < c; i++) {
        indent += " ";
    }
    console.log(indent + "fibonacci(" + n + ")");
    if (n < 2) {
        return 1;
    } else {
        return fibonacci(n - 2, c + 4) + fibonacci(n - 1, c + 4);
    }
}

console.log(fibonacci(7, 0));

Output:

fibonacci(7)
    fibonacci(5)
        fibonacci(3)
            fibonacci(1)
            fibonacci(2)
                fibonacci(0)
                fibonacci(1)
        fibonacci(4)
            fibonacci(2)
                fibonacci(0)
                fibonacci(1)
            fibonacci(3)
                fibonacci(1)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
    fibonacci(6)
        fibonacci(4)
            fibonacci(2)
                fibonacci(0)
                fibonacci(1)
            fibonacci(3)
                fibonacci(1)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
        fibonacci(5)
            fibonacci(3)
                fibonacci(1)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
            fibonacci(4)
                fibonacci(2)
                    fibonacci(0)
                    fibonacci(1)
                fibonacci(3)
                    fibonacci(1)
                    fibonacci(2)
                        fibonacci(0)
                        fibonacci(1)

Values at the same level of indentation are summed to produce the result for the previous level of indentation.

2 of 14
45

There are many good answers here, but I made this diagram which helps better explain the outcome of the function. The only values that will ever be returned are 1 or 0 (your example returns 1 for n < 2, but should instead return n).

This means that each recursive call will eventually wind up returning either a 0 or 1. Those end up being "cached" in the stack and "carried up" into the original invocation and added together.

So if you were to draw this same diagram out for each value of 'n' you could manually find the answer.

This diagram roughly illustrates how every function is returned for fib(5).

This shows the control flow, i.e. the order of execution for the functions. Remember code is always executed left->right and top-> bottom. So whenever a new function is called it is paused and then the next invocation occurs.

The following illustrates the actual control flow based on your original post. Please note the base condition is if (n <= 0) {return 0} else if (n <= 2) {return 1;} for simplification:

1. fib(5) {
    return fib(4) + fib(3);
2.   fib(4) {
      return fib(3) + fib(2);
3.     fib(3) {
        return fib(2) + fib(1);
4.       fib(2) {
A=        return 1;
         };
5.       fib(1) {
B=        return 1;
         };
C=      return 2; // (1 + 1)
       };
6.     fib(2) {
D=      return 1;
       };
E=    return 3; // (2 + 1)
     };
7.   fib(3) {
      return fib(2) + fib(1);
8.     fib(2) {
F=      return 1;
       };
9.     fib(1) {
G=      return 1;
       };
H=    return 2; // (1 + 1)
     };
I=  return 5; // (3 + 2)
   };
🌐
Programiz
programiz.com › javascript › examples › fibonacci-recursion
JavaScript Program to Display Fibonacci Sequence Using Recursion
// program to display fibonacci sequence using recursion function fibonacci(num) { if(num < 2) { return num; } else { return fibonacci(num-1) + fibonacci(num - 2); } } // take nth term input from the user const nTerms = prompt('Enter the number of terms: '); if(nTerms <=0) { console.log('Enter ...
Discussions

Can you explain the logic behind a recursive fibonacci function?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
15
9
November 23, 2022
Can I get clarification on the fibonacci javascript exercise?
You can do all of that inside of one function. -Take the given number and check if it should be accept. -Then iterate through the sequence until the given position. For this, the calculation should be simple, 1 + 1 = 2, 1 + 2 = 3, and so on. -Return the member of the sequence in that position. You'll need at least one temp variable and because of the way fibonacci works, you'll need to adjust the loop properly. More on reddit.com
🌐 r/theodinproject
4
2
November 21, 2022
I just implemented the Fibonacci sequence as a one-liner, arrow function as a Javascript newbie, feeling VERY happy and proud of it
Nice! :) Here is one in Clojure, defining the infinite Fibonacci sequence. > (def fib (lazy-cat [0 1] (map + fib (rest fib)))) > fib (0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 ...) More on reddit.com
🌐 r/learnprogramming
98
585
December 14, 2019
Fibonacci recursion is wrecking my brain. What's going on with the console.log here? I thought I understood what this code was doing but I was wrong. Here I am trying to evaluate what the fibonacci number is at the 5th position (i.e. 5th position of this fibonnaci sequence 1, 2, 3, 5, 8).
This subreddit is for anyone who wants to learn JavaScript or help others do so. Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend · Create your account and connect with a world of communities More on reddit.com
🌐 r/learnjavascript
4
7
July 23, 2017
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Recursion with fibonacci - JavaScript - The freeCodeCamp Forum
June 2, 2021 - Tell us what’s happening: Describe your issue in detail here. ok so, im like 95% certain my code works but it times out the test. am i making a mistake or is it too memory heavy? **Your code so far** function sumFibs(num) { var result = 0 function fibonacci(num) { if (num
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-program-to-display-fibonacci-sequence-using-recursion
JavaScript Program to Display Fibonacci Sequence Using Recursion - GeeksforGeeks
July 29, 2024 - The base case for the recursion is when n is less than or equal to 1. In this case, we simply return n itself, as the Fibonacci sequence starts with 0 and 1. For any other value ofn, we recursively call the fibonacci function with n - 1 and ...
🌐
Medium
medium.com › developers-writing › fibonacci-sequence-algorithm-in-javascript-b253dc7e320e
Fibonacci sequence algorithm in Javascript | by devlucky | Developers Writing | Medium
March 3, 2016 - Fibonacci sequence algorithm in Javascript Probably one of the most famous algorithms ever, but still lot of people struggles when trying to find an efficient solution. Let me introduce you to the …
🌐
sebhastian
sebhastian.com › fibonacci-recursion-javascript
Find Fibonacci sequence number using recursion in JavaScript | sebhastian
January 30, 2021 - Since the base case for the function is n < 2, this means you can trigger the recursive call once when you pass the number 2. Here’s how a fib(2) call should resolve. Notice how the recursive call is following the formula: ... You now have ...
Find elsewhere
🌐
Medium
medium.com › @apestruy › iterative-and-recursive-solutions-to-the-fibonacci-sequence-interview-question-16e226a27987
Iterative and Recursive Solutions to the Fibonacci Sequence Interview Question in JavaScript | by Alexandra Pestruyeva | Medium
April 16, 2020 - With every run of the loop, sequenceArray gets an element pushed to the back until i is equal to 7. At the final execution of the function, we add the numbers at index (i - 1) and index (i - 2) of the previously returned sequenceArray. This results in index (7 - 1) and index (7 - 2), which are indexes 6 and 5, respectively. The element at the sixth index is 8, and the element at the fifth index is 5. So, the last element to be pushed to the back of sequenceArray is 13, which is their sum. let recursive_fibonacci = function (n) { if (n <= 1) { return [0, 1]; } else { let sequenceArray = recursive_fibonacci(n - 1); sequenceArray.push(sequenceArray[sequenceArray.length - 1] + sequenceArray[sequenceArray.length - 2]); return sequenceArray; } };recursive_fibonacci(7);
🌐
W3Schools
w3schools.com › dsa › dsa_algo_simple.php
DSA Simple Algorithm
To replace the for loop with recursion, we need to encapsulate much of the code in a function, and we need the function to call itself to create a new Fibonacci number as long as the produced number of Fibonacci numbers is below, or equal to, 19.
🌐
Reintech
reintech.io › blog › solving-fibonacci-series-using-recursion-javascript
Solving Fibonacci Series Using Recursion in JavaScript | Reintech media
September 10, 2023 - This function works by checking if the input number is less than 2. If it is, it simply returns the number. If not, it calls itself with the two preceding numbers and adds the results, effectively creating the Fibonacci sequence.
🌐
Scaler
scaler.com › home › topics › fibonacci series in javascript
Fibonacci Series in JavaScript - Scaler Topics
March 19, 2024 - We can see that there is a lot of repetition of function in the case of the recursive approach. Time complexity is: O(2^n) Space complexity is: O(n), which comes out to be the maximum depth of the recursive tree. We can also generate the reversed Fibonacci series in javascript using a loop or recursive approach.
🌐
Vultr Docs
docs.vultr.com › javascript › examples › display-fibonacci-sequence-using-recursion
JavaScript Program to Display Fibonacci Sequence Using Recursion | Vultr Docs
November 14, 2024 - Decide the length of the Fibonacci sequence to display. Iterate from 0 up to the chosen length, invoking the recursive function during each iteration.
🌐
AlgoCademy
algocademy.com › link
Recursive Fibonacci in JavaScript (Time Complexity
To solve this problem, we can start with a naive recursive approach: Check the base cases: if n is 0 or 1, return n. For n >= 2, return the sum of the two preceding Fibonacci numbers.
🌐
The Odin Project
theodinproject.com › lessons › javascript-recursion
Project: Recursion | The Odin Project
First up create a file and tackle the fibonacci sequence: Using iteration, write a function fibs which takes a number and returns an array containing that many numbers from the Fibonacci sequence.
🌐
Cratecode
cratecode.com › info › javascript recursion: fibonacci sequence
JavaScript Recursion: Fibonacci Sequence | Cratecode
August 29, 2024 - Now, let's implement this in JavaScript using recursion. function fibonacci(n) { if (n <= 1) { return n; } else { return fibonacci(n - 1) + fibonacci(n - 2); } } console.log(fibonacci(10)); // Output: 55
🌐
Vultr Docs
docs.vultr.com › javascript › examples › print-the-fibonacci-sequence
JavaScript Program to Print the Fibonacci Sequence
November 13, 2024 - In this recursive method, the fibonacci function calls itself to compute each term of the sequence. The printFibonacciSeries function iteratively calls the fibonacci function for each term up to the nth term.
🌐
Medium
medium.com › codex › fibonacci-sequence-javascript-recursion-memoization-74d997900ff8
Fibonacci Sequence — JavaScript, Recursion & Memoization | by Nicoll Oliver | CodeX | Medium
July 10, 2021 - Now that we have a clue what the Fibonacci Sequence is, let’s do some recursive problem solving. PROBLEM: Write a function ‘fib(n)’ that takes in a number as an argument. The function should return the n-th number of the Fibonacci Sequence.
🌐
Medium
medium.com › quick-code › fibonacci-sequence-javascript-interview-question-iterative-and-recursive-solutions-6a0346d24053
Fibonacci sequence JavaScript interview question. Iterative and Recursive solutions. | by Lucya Koroleva | Quick Code | Medium
June 4, 2021 - Basically our fib function will continue to recursively call itself creating more and more branches of the tree until it hits the base case, from which it will start summing up each branch’s return values bottom up, until it finally sums them ...
🌐
Frontend Masters
frontendmasters.com › courses › functional-first-steps-v2 › iteration-vs-recursion-fibonacci-exercise
Iteration vs Recursion Fibonacci Exercise - Functional JavaScript First Steps, v2 | Frontend Masters
Let's look at the recursive implementation of the Fibonacci calculator. So here. >> Anjana Vakil: Well, we still know what the first two numbers of the Fibonacci sequence are right? And because it is a recursive function, we definitely need a base case, at least one wink.
🌐
Medium
medium.com › @eddgr › practicing-recursion-in-javascript-by-returning-the-fibonacci-sequence-195b41614060
Practicing recursion in JavaScript by returning the Fibonacci Sequence | by Edgar Ong | Medium
July 18, 2019 - We forgot about some edge cases. What if the function is called and the argument is less than 2? It would cause an infinite loop so we need to add checks. ... const fib = length => { if (length < 2) { return "You won't get a Fibonacci sequence with this!" } if (sequence.length === length) { return sequence } else { const lastTwo = sequence.slice(-2) sequence.push(lastTwo[0] + lastTwo[1]) fib(length) }}