# Basic JavaScript #112: Use Recursion to Create a Countdown

In the example function:

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

I’m having trouble (with recursion in general) understanding at what point 5 is pushed to the array if countArray is always n - 1. Wouldn’t the first value that’s pushed to the array be 4 if n - 1 = 4 on the first call?

Thanks in advance for any explanations!

Edit: Passing the exercise was fairly straightforward, but in my own code I still don’t understand when 5 is sent to the array.

function countdown(n) {
if (n < 1) {
return [];
} else {
const countArray = countdown(n - 1);
countArray.unshift(n);
return countArray;
}
}

console.log(countdown(5)); // [5, 4, 3, 2, 1]

Recursion can be hard to understand, but this video and a step by step of the code running might help.

The visualization made it more confusing for me, as if 5 populated the array even before the conditional statements were executed. Thank you for the video though!

the video will explain things better then i probably could. It explains the call stack, which is a major part of where everything kinda “hangs out” while recursion is doing its thing. feel free to ask more questions if this is not enough and google isn’t helping.

Are recursive functions fairly common in codebases? This subject is flying over my head, and I’m a little terrified

Im not a professional developer yet, but from some of the posts on here from people who are you don’t see it to often. A normal loop is faster and far more common, but recursion can be simpler to read and better for certain tasks. And it usually takes some time for people to fully grasp what is going on with all the function calls and the call stack in recursion.

edit: just saw your edit at the top. 5 is being added last to the array. the first thing that actually gets returned from all these function calls is an empty array, then all the numbers stored in the call stack from the other function calls get unshifted to that returned array.

Thank you for the resources. The code visualization tool you provided and this reference I found helped me realize that countArray.push(n); occurs after all the recursive call returns. Even though n = 5 at the initial function call, because of backwards recursion, that is the last function call that executes.

1 Like

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