1

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.

billyhalim25
  • 323
  • 1
  • 2
  • 16
  • http://stackoverflow.com/questions/10638059/javascript-debugging-line-by-line-using-google-chrome – Quentin May 16 '17 at 11:04
  • After recursion it will call second `document.write`. – Shubham May 16 '17 at 11:04
  • The write instruction is located after the recursive function call, hence the execution will take place after the recursive call ;-) – Eineki May 16 '17 at 11:05
  • In javascript, recursion works the same as in any other imperative programming lagnuage. To find out in which order the statements are executed, you can try it out or think about an example. – Aloso May 16 '17 at 11:07

3 Answers3

3

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)
Weedoze
  • 13,683
  • 1
  • 33
  • 63
  • Is it executed after ALL recursion or after the first recusion? – billyhalim25 May 16 '17 at 11:11
  • @billyhalim25 You can run the code snippet. You will see that it will display all iteration from 1 to 4. Then it will display the numbers with `foo` – Weedoze May 16 '17 at 11:12
  • Yes, I understand. But how do the program remember the value for n in `document.write(n + " Foo
    ");` as these lines are queued until all recursion finished?
    – billyhalim25 May 16 '17 at 11:16
2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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.