Hi,
This is from the “Use Recursion to Create a Countdown” challenge in Basic JavaScript. I’m just referencing the example they give in the challenge here. I’m trying to figure out if I’m thinking about this correctly:
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5));
So as I understand it, this code is kind of divided up into two parts. You have the recursive call that happens first. We start with whatever our n is equal to (in this case 5) and continue to recursively call the function (5 - 1) = 4, (4 - 1) =3, (3 - 1) = 2, (2 - 1) = 1, (1-1) = 0. We’ve now reached our base case (n < 1). The code tells us this will return an empty array ( [ ]).
So now we have a stack of “half” calls that still need to be “operated” on in order to complete the code:
[ ]
1
2
3
4
5
We now jump to our next line of code which is countArray.push(n). This will take each of the recursive calls in our stack and push that value onto an array. The stack starts from the top or the last call. So we begin with the empty array [ ] and push each subsequent value onto the array [1, 2, 3, 4, 5]. When the entire stack has been run through, we return the array. Is this reasoning correct?