(function foo(i) { console.log(i); if (i === 3) { return; } else { foo(++i); console.log(i); } }(0)); 

Conclusion:

0
one
2
3
3
2
one

I do not understand where 3, 2, 1 come from and why are they displayed at the end?

    1 answer 1

    Everything is quite simple. In the clause with else no clause with return, but there is a transition to the sentence with output to the console

     (function foo(i) { console.log(i); if (i === 3) { return; } else { foo(++i); console.log(i); } }(0)); 

    Each function call prints first the initial value of the argument, and then the same argument value, incremented by 1.

    Therefore, inside the first function call will be printed

     0 и 1 

    inside the second call will be printed

     1 и 2 

    inside the third call will be printed

     2 и 3 

    inside the fourth call only 3 will be printed

     3 

    since there is a return clause

      if (i === 3) { return; } 

    If you now put the function calls inside each other, then you will get the specified result.

     0 1 2 3 3 2 1 | | | | | | | | | |___| | | | |_______| | |___________| 

    To make it clearer, replace the statement with the function call.

     foo(++i); 

    ha offer

     ++i; 

    As a result, you will get this function.

     (function foo(i) { console.log(i); if (i === 3) { return; } else { //foo(++i); ++i; console.log(i); } }(0)); 

    and see what it will bring as a result of the work.

    • It seemed to me according to this scheme should be 0, 1, 1, 2, 2, 3, 3 - S.Sumyilo
    • @S.Sumyilo Between the values ​​0 and 1, you must insert the output that will generate the function call, which is located between the outputs of these two values. - Vlad from Moscow
    • @ S.Sumyilo The function parameters form the scope within the function. - Vlad from Moscow