How to understand this script?
-
I started learning recursion, can you tell me how it works?
I understand the first three steps, but I can't understand further.
1.n = 5
2.n! == 5
3.return myFun (n - 1) + '' + n; // Output: 4 5. If the initial output is 4 5, how do the rest of the numbers get to 4 5?
4. Further I don’t understand, the variable n doesn’t change, it seems like how other numbers are obtained then?
function myFun(n) { if (n === 1) return 1; return myFun(n - 1) + ' ' + n; } myFun(5); // 1 2 3 4 5
JavaScript Anonymous, Jul 28, 2020 -
Take a walk for a start.
Recursion will start returning a result when it reaches the very end and results will start returning from the very end. Hence, it turns out that 5 was sent, but the output started from 1, because return did not work before, it called the myFun function, and the result began to return when this ifif (n == = 1) return 1;
, in which myFun is no longer called and, accordingly, the recursion ends and return begins to return a response.Evangeline Bruce
1 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!