Maybe someone can help me understand this. I got the code below to work just by trying different things until it took, but I’m confused by why it works.
It seems to me that if I pass the function the argument of 5, it would process that argument first, and it would become the first item in the countArray constant. Therefore the next iteration would be 4, and then 3., and then so on to 1. What confuses me is this: if I’m adding the result of each subsequent iteration to the front of the array using .unshift()… shouldn’t countArray resolve to [1,2,3,4,5] at the end?
ƒ countDown(n) {
if (n < 1) {
return [];
} else {
const countArray = countDown(n - 1);
countArray.unshift(n);
return countArray;
}
}
countDown(5)
[5,4,3,2,1]
Challenge: Use Recursion to Create a Countdown
Link to the challenge: