J
J
justifycontent2020-11-11 03:46:44
JavaScript
justifycontent, 2020-11-11 03:46:44

How to understand this script?

I started to study recursion, 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 4 5 is initially output, how do the rest of the numbers end up before 4 5?
4. Further, I don’t understand, the variable n does not change, like, how then do other numbers turn out?

function myFun(n) {
  if (n === 1) return 1;

  return myFun(n - 1) + ' ' + n;
}

myFun(5);

// 1 2 3 4 5

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tukreb, 2020-11-11
@justifycontent

You walk for a start.
The recursion will start returning the result when it reaches the very end and the results will start returning from the very end. From here it turns out that they sent 5, but the output started from 1, because return, before that, did not work, it called the myFun function, and the result began to return when this if worked , in which myFun is no longer called and, accordingly, the recursion and return end starts returning a response. if (n === 1) return 1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question