0

I can't seem to fully understand the fundamentals off recursive functions. We have this code:

function myself (n) {
if (n <= 1) {
    return 1;
}
return n * myself(n-1);
}
myself(5);

I get that 5 would be multiplied by 4 equals to 20 and then 20 multiplied by 3 and so on but what I don't quite get is how can 'n' be two different numbers in one function.

Benas Lengvinas
  • 414
  • 1
  • 4
  • 16

2 Answers2

6

how can 'n' be two different numbers in one function

Variable scope exists for a function invocation, not a function definition.

Each call to myself gets an n variable of its very own, which is unrelated to the previously existing ns.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    Was typing dozens of lines about the virtual machine's call stack when I read your answer. Could not agree more with @TomerW. – Tobias Nov 06 '16 at 19:48
  • Thanks for the answer, helped a lot. – Benas Lengvinas Nov 06 '16 at 20:06
  • @Quentin so i thought that i got it but i didn't :D so when myself(n-1) finishes the 'function myself (n // is it 4 now?). And when n is multiplied by n-1 where does the result go? I guess i don't fully understand the scope either.... – Benas Lengvinas Nov 06 '16 at 21:04
  • "when myself(n-1) finishes the 'function myself (n // is it 4 now?)." — Which `n`? As I said, there are multiple `n`s – Quentin Nov 07 '16 at 09:26
  • "And when n is multiplied by n-1 where does the result go?" — That never happens. `n - 1` is the argument to a function call, it is the return value of that function call which is multiplied by `n`. As for where it goes, there is a `return` statement on the left hand side, so it is returned to wherever it was called from. – Quentin Nov 07 '16 at 09:27
2

n is a local variable. Your example would execute as follows.

myself(5) 
return 5 * myself(4)
return 5 * (return 4 * myself(3))
return 5 * (return 4 * (return 3 * myself(2)))
return 5 * (return 4 * (return 3 * (return 2 * myself(1))))
return 5 * (return 4 * (return 3 * (return 2 * return 1)))
return 5 * (return 4 * (return 3 * (return 2 * 1)))
return 5 * (return 4 * (return 3 * 2))
return 5 * (return 4 * 6)
return 5 * 24
return 120

n contains a reference to the number parameter at each invocation.

Ely
  • 10,860
  • 4
  • 43
  • 64