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
🌐
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 ...
🌐
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 ...
Discussions

Recursion with fibonacci
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 sumF… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
June 2, 2021
recursion - How does the fibonacci recursive function "work"? - Stack Overflow
I'm new to Javascript and was reading up on it, when I came to a chapter that described function recursion. It used an example function to find the nth number of the Fibonacci sequence. The code ... More on stackoverflow.com
🌐 stackoverflow.com
fibonacci using recursion
Don’t use input unless the prompt says to - homework graders have to handle it in a special way, and if they’re not expecting to, your program just blocks on input. More on reddit.com
🌐 r/learnpython
13
9
January 14, 2023
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
🌐
Reintech
reintech.io › blog › solving-fibonacci-series-using-recursion-javascript
Solving Fibonacci Series Using Recursion in JavaScript | Reintech media
September 10, 2023 - Dive deep into the concept of the Fibonacci series and learn how to solve it using recursion in JavaScript. This comprehensive tutorial is designed to help both beginners and advanced developers.
🌐
W3Resource
w3resource.com › javascript-exercises › javascript-recursion-function-exercise-6.php
JavaScript recursion function: Get the first n Fibonacci numbers - w3resource
var fibonacci_series = function (n) { // Base case: if n is less than or equal to 1, return the base series [0, 1]. if (n <= 1) { return [0, 1]; } else { // Recursive case: generate the Fibonacci series up to (n - 1). var s = fibonacci_series(n ...
🌐
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
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)
   };
🌐
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.
Find elsewhere
🌐
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 - This function makes two recursive calls to itself, calculating Fibonacci numbers for n-1 and n-2 until reaching the base cases where n is 0 or 1. In these cases, it directly returns n, as the Fibonacci sequence starts with 0, 1.
🌐
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 …
🌐
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.
🌐
JavaScript Today
javascripttoday.com › blog › fibonacci-series-in-javascript
JavaScript Today - Daily Insights for Developers - A Look At The Fibonacci Sequence: A Recursive and Iterative Solution
Surely, if you were to implement ... the challenge is quite simple. The directions are as follows: Print out the n-th entry in the fibonacci series......
🌐
Medium
medium.com › codex › fibonacci-sequence-javascript-recursion-memoization-74d997900ff8
Fibonacci Sequence — JavaScript, Recursion & Memoization | by Nicoll Oliver | CodeX | Medium
July 10, 2021 - The function should return the n-th number of the Fibonacci Sequence. In our case, let’s do the 8th number. We want the 8th number of the sequence — how do you go about this? Let’s draw it out: ... Can you recognize the pattern that it’s following? This patter will eventually end and hit its base case. Remember here that these numbers counting down is n, not the actual numbers in the sequence. Let’s try this function below: ... This is used because the first two numbers of the sequence (not including 0) are 1's.
🌐
Medium
jacksongrowson.medium.com › solving-the-fibonacci-sequence-using-javascript-8ef9d3d4123b
Solving the Fibonacci Sequence Using JavaScript | by Jackson Beytebiere | Medium
February 19, 2021 - In this blog I will solve the problem “given a number n, find the value of the nth iteration of the Fibonacci Sequence.” I will use a bottom-up solution, a recursive solution and finally a pretty neat constant time solution. All my solutions will be in JavaScript.
🌐
sebhastian
sebhastian.com › fibonacci-recursion-javascript
Find Fibonacci sequence number using recursion in JavaScript | sebhastian
January 30, 2021 - Following the illustration for ... calling fib(1) and fib(0) again. The number of recursive calls you reduce with memoization will increase as you call on the larger Fibonacci nth term....
🌐
Quora
quora.com › Can-you-optimize-your-implementation-of-generating-the-Fibonacci-series-using-recursion-JavaScript-algorithm-array-recursion-fibonacci-sequence-solutions
Can you optimize your implementation of generating the Fibonacci series using recursion (JavaScript, algorithm, array, recursion, fibonacci sequence, solutions)? - Quora
Answer: Yes. See Garry Hodgson's answer to Why is the Fibonacci calculation preferred to use recursion than iteration?, which shows the code in Python. See below my Erlang code and some times I got on my PixelBook. You asked about JavaScript, but it’s not hard to translate once you get the idea.
🌐
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 - Since this causes the function to go into a loop, it is required that recursive functions have a termination point, so that the function can stop executing. In this solution, the termination point is that n must be less than or equal to 1. This causes the array [0, 1] to be returned because those are the first two numbers in the Fibonacci Sequence.
🌐
Cratecode
cratecode.com › info › javascript recursion: fibonacci sequence
JavaScript Recursion: Fibonacci Sequence | Cratecode
August 29, 2024 - For a quick introduction on recursion, you can check out this article. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The beginning of the sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on. Now, let's implement this in JavaScript ...
🌐
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 all up and returns an integer equal to 5. It might take a moment to sink in, so take some time to look at the tree and you will understand what’s happening there. For the Fibonacci sequence, it is highly recommended to learn JavaScript.
🌐
Studytonight
studytonight.com › javascript-programs › javascript-program-to-generate-fibonacci-sequence-using-recursion
JavaScript Program to Generate Fibonacci Sequence Using Recursion - Studytonight
Setting up a recursive function that adds the two previous numbers in the sequence to get the next one, and then calling that function over and over again until the number of terms you want is reached, is how the process works.