pedroyanky pedroyanky - 6 months ago 23
Javascript Question

Understanding how a recursive function works in javascript

I am a little bit confused on the exact execution timeline in which the following function runs. I saw this code on the MDN guide:

function foo (i) {
if (i<0) return;
console.log('begin' + i);
console.log('end' + i);

Based on my knowledge of how functions work, this is what I thought, though my knowledge is inadequate:

I think when the function
is called, it will go to the function and check the condition
if i < 0
, then it will run the next code
console.log('begin:' + i)

After that, the next line of code is executed, since JavaScript execute line by line, the next line of code which is
will be executed.

It takes the current value of
which is
minus 1, so
is called and the execution continues.

My question is: Is my understanding correct?. If no please explain what this code is doing, otherwise can anyone explain breiefly when will the function stop being called?


What happens when you call foo(3) is as follows (in pseudocode):

execute foo(3)
    3 is greater than 0 thus log(begin 3)
    execute foo(2)
        2 is greater than 0 thus log(begin 2)
        execute foo(1)
            1 is greater than 0 thus log(begin 1)
            execute foo(0)
                0 is equal to 0 thus log(begin 0)
                execute foo(-1)
                    -1 is less than 0 thus return
                log(end 0)
            log(end 1)
        log(end 2)
    log(end 3)