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.

4
  • stackoverflow.com/questions/10638059/… Commented May 16, 2017 at 11:04
  • After recursion it will call second document.write. Commented May 16, 2017 at 11:04
  • The write instruction is located after the recursive function call, hence the execution will take place after the recursive call ;-) Commented May 16, 2017 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. Commented May 16, 2017 at 11:07

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Is it executed after ALL recursion or after the first recusion?
@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
Yes, I understand. But how do the program remember the value for n in document.write(n + " Foo<br>"); as these lines are queued until all recursion finished?
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);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.