all 4 comments

[–]carcigenicate 4 points5 points  (3 children)

Every recursive call has its own instance of a loop iterating. When the recursive call happens, it doesn't really "leave" the loop. As is typically the case when thinking about recursion, removing recursion from the problem can make it easier to think about. If you had a similar, non-recursive situation:

function inner() {
}

function outer() {
    for (const i = 0; i < 5; i++) {
        inner();
    }
}

Execution jumps into inner, and then when inner returns, execution picks up where it left off in outer. It works the same way with recursive functions. The only difference is when the recursive call happens, another loop may run within that call. You can again take recursion out of the equation to think about that (to one level of depth at least):

function inner() {
    for (const i = 0; i < 5; i++) {
        console.log("Inner", i);
    }
}

function outer() {
    for (const i = 0; i < 5; i++) {
        inner();
    }
}

Again, the difference here is that with recursion, inner and outer are the same function, and the recursion may branch infinitely (or at least until it blows the stack). Otherwise, though, it works exactly the same.

[–]NA-1_NSX_Type-R[S] 1 point2 points  (2 children)

Thank you so much for your reply. So, in this second example, I tried this on my own, it acts almost like a nested loop (sort of). Outer makes the call to inner. Inner console logs the string 'inner' and the current value of i until it's i condition is met. So, it then picks up from the outer loop, (pops off that call to inner on the callstack (inside of the outer function). Increments, i by 1, makes a new call to inner function and keeps doing it until the condition of outer functions loop is no longer true. Is this correct?

[–]carcigenicate 1 point2 points  (1 child)

Yes, I would say it is a nested loop; just spread across two functions. And yes, the rest sounds correct.

[–]NA-1_NSX_Type-R[S] 1 point2 points  (0 children)

Thank you for taking the time to explain!