I don't entirely understand this Recursive Function

Can someone please explain what each of the 3 lines of code within the else statement does please. How does countArray.push(n); work if countArray is not an Array? Does return countArray; recall the function and return the current array? Also, if possible, can someone please expand the line: return countArray;.

  **Code from the current challenge(Not my code)**

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

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

The important thing to remember about recursion is that every function call is independent.

So here

this line makes an array counting up to n - 1

and then this line

pushes n onto that array.

1 Like

Let’s use a very simple example. What does the following function call return?

countup(0);

Since n is less than 1 then the countup function will return an empty array ([]).

Now let’s look at another simple example:

countup(1)

Since n is greater than 0 we will hit the else block and do the following:

const countArray = countup(0);

We pass 0 into countup because n-1 in this case is 1-1. And we already know what countup(0) returns, right? It returns an array. It may be an empty array, but it is an array nonetheless. So after we call countup recursively the value of countArray will be an empty array. So as you can see, countArray is an array!

The logical jump here is that this also works when we call countup(2), or countup(3), or as high as you want to go. In the end, we will always reach the base case and get that empty array because each time we call countup recursively we are reducing the number by 1.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.