0

I have one simple recursive function which adds all it's previous numbers.

function add(n) {
  if (n == 0) {
    return 1; // when it reaches here it should give me 1.
  }
  return n + add(n - 1);
}

console.log( add(5) ); // give me 16

when the execution reaches line number 3, it should return me 1, but it is return me 16. how return is actually working here ?

2 Answers 2

3

Recursion pauses the program at recursion step call and continue solving the sub problem and when a base condition is hit all the return statements pass the control back to the callee statement.

So

add(5)-->return 5+add(4)
                     |-->return 4+add(3)
                                   |-->return 3+add(2)
                                                 |-->return 2+add(1)
                                                                 |-->return 1+add(0)//base condition, return 1 for add(0) which in return return 2

1-->2-->4-->7-->11-->16 (In reverse)
Sign up to request clarification or add additional context in comments.

3 Comments

this happens only in recusrive case ?
Yes recursion works in this way.You may follow this link for some basic understanding. freecodecamp.org/news/…
You may be thinking of it like you would a while loop that can exit with a return statement. Instead of recursion which returns it back to the calling function which returns that back to its calling function, and so on. At least that was the problem for me when I started recursions.
3

that is because the conditional statement that your line 3 is in says to return 1 only if the argument n passed in is equals to 0. The function you are calling at the end of the code is passing in an argument of 5.

the first return statement would only work if condition in the if statement is true, otherwise it goes to the second return which calls the function again within itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.