Each time it ends a recursion, (so it reaches the if (rest.length == 0)
) it goes back to the caller. The caller instead of going to back to its own caller (as is usual) calls the recursion again.
Take a look to the example with a bunch of console.log
that can explain things
function string_recurse(active, rest, i) {
if (rest.length == 0) {
console.log(active);
} else {
console.log('Calling 1st recursion at depth', i);
string_recurse(active + rest.charAt(0), rest.substring(1, rest.length), i + 1);
console.log('Ended first recursion, calling second one at depth', i);
string_recurse(active, rest.substring(1, rest.length), i + 1);
console.log('Ended second recursion at depth', i);
}
}
string_recurse("", "abc", 0);
Or, if it is better, here a schema that tries to explain the sequence in the call:
f("", "abc")
|
|
--- f("a", "bc")
|
|
--- f("ab", "c")
|
|
--- f("abc", "") -> console.log()
--- f("ab", "") -> console.log()
|
|
--- f("a", "c")
|
|
--- f("ac", "") -> console.log()
--- f("a", "") -> console.log()
|
|
--- f("", "bc")
|
|
--- f("b", "c")
|
|
--- f("bc", "") -> console.log()
--- f("b", "") -> console.log()
|
|
--- f("c", "") -> console.log()
You can see from the start to the end the order of the calls, and you can see every function or has two children or print the value of active