Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can some explain how return statements work with recursion in javascript?

I already checked forum, I saw a few with a similar title but not one that answered my question. I noticed if I create a recursion function the return statement returns after the termination statement it looks like. Could someone explain how this works to me? thanks

function recur(n=10){
  if(n===0){
    return "";
  }
  console.log(n);
  return "A" + recur(n-1);
}

recur()

The end result is:

10
9
8
7
6
5
4
3
2
1
"AAAAAAAAAA"

I expected it to return A for each instance of the function, because I thought every statement in the function definition would be called for every instance of the function, like this:

10
"A"
9
"A"
8
"A"
7
"A"
6
"A"
5
"A"
4
"A"
3
"A"
2
"A"
1
"A"

So to reiterate why didn't the function return A like I was expecting, what pattern of how a function operates am I misunderstanding?

like image 630
Brandon Avatar asked Aug 10 '26 14:08

Brandon


1 Answers

Working it out like this might help your understanding:

recur(5) = "A" + recur(4)
         = "A" + ("A" + recur(3))
         = "A" + ("A" + ("A" + recur(2)))
         = "A" + ("A" + ("A" + ("A" + recur(1))))
         = "A" + ("A" + ("A" + ("A" + ("A" + recur(0)))))
         = "A" + ("A" + ("A" + ("A" + ("A" + ""))))
         = "A" + ("A" + ("A" + ("A" + ("A"))))
         = "A" + ("A" + ("A" + ("AA")))
         = "A" + ("A" + ("AAA"))
         = "A" + ("AAAA")
         = "AAAAA"

So recur(5) returns "AAAAA". You should be able to extend this reasoning to show that recur(10) returns "AAAAAAAAAA".

You are printing the value of n, an integer, each time, and not printing the result of each recursive invocation of recur. The "AAAAAAAAAA" you are seeing at the end is the result of your console (shell, REPL, ...) displaying the result of everything you execute; in this case you see this at the end of your invocation of recur(), which is the same as recur(10).

If you want to “trace” the function, you can assign the result to a variable and then return it. Try this:

$ node
> function recur(n=10){
...   if(n===0){
.....     return "";
.....   }
...   let result = "A" + recur(n-1);
...   console.log(n, result);
...   return result;
... }
undefined
> recur()
1 'A'
2 'AA'
3 'AAA'
4 'AAAA'
5 'AAAAA'
6 'AAAAAA'
7 'AAAAAAA'
8 'AAAAAAAA'
9 'AAAAAAAAA'
10 'AAAAAAAAAA'
like image 141
Ray Toal Avatar answered Aug 12 '26 04:08

Ray Toal