billyhalim25
billyhalim25

Reputation: 343

Recursion on Javascript

I want to know how the recursion works in Javascript. I take an example below:

function abc(n){
     document.write(n + "<br>");
     if (n < 4){
         abc(n+1);
         document.write(n + "<br>");
     }
}

My attention is at the 5th line. When will the 5th be executed? Is the 5th line executed before or after the recursion?

Thanks.

Upvotes: 1

Views: 119

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386550

It is executed aber the first finished recursion. It follows the Depth-first search principle.

    levels                 comment
-------------  ----------------------------------
1
    2
        3
            4  end of recursion calls, max depth
        3
    2
1

function abc(n){
     document.write(n + "<br>");
     if (n < 4){
         abc(n+1);
         document.write(n + "<br>");
     }
}

abc(0);

Upvotes: 2

Adrian Makowski
Adrian Makowski

Reputation: 169

It will be executed after recursion. Recursion invokes functions in functions until conditions are met. In your case variable n should be less than 4 for recursion to go into "deeper" level of function.

abc(1) -> abc(2) -> abc(3)

So you will have 3 synchronous function invocations before program can go to other lines.

Upvotes: 1

Weedoze
Weedoze

Reputation: 13943

It will be executed after the recursion

function abc(n){
     document.write(n + "<br>");
     if (n < 4){
         abc(n+1);
         document.write(n + " Foo<br>");
     }
}

abc(1)

Upvotes: 3

Related Questions