(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?
(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?
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.
Source: https://ru.stackoverflow.com/questions/620902/
All Articles