What is happning in this code? (Recursion)

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

After running the above code it returns an array [1, 2, 3, 4, 5] But push() adds new values at the end of an array so when value of n was 5 is should push 5 to the end of the array and when value of n got 4 it should push 4 at the end of the array like [5,4]. So why not it is returning [5,4,3,2,1] ? It is hard to understand what is happening in this code probably because of this recursion. Isn’t unshift() (which add new values to start of the array) should return [1,2,3,4,5] and push() [5,4,3,2,1] why opposite is happening?

Recursions is a difficult subject, even for experienced coders. I would suggest searching the forum for any of the threads on the forum discussing this exact function - many have detailed explanations.

Learning to search for answers is a very, very, very useful skill for developers. I do it a few (sometimes many) times a day searching through repo issues or Stack Overflow to see if someone has already explained my problem. On the job, you usually won’t be able to ask people to explain things to you, step by step.

Search and see what you can find. If after that, if that doesn’t help, check back and we’ll see if we can clarify it further.

1 Like

At the first time I saw recursion I told myself, we can use this for avoiding the loops, then I learnt that those using stacking operations whenever called so making the program getting slow. Real interesting and difficult subject thanks for making me feel better :slight_smile:

Yeah, in certain cases recursion can be slower. There are ways to mitigate this, but it is generally true. But for certain specific subset of problems, recursion can be an incredibly elegant solution. And speed is not always the most important thing.

1 Like