Tell us what’s happening:
I’ve completed the challenge just fine, I just don’t get how the recursion works (and yes, I’ve read some articles on it, which is why I’m asking)
So here’s how I understand it. If I run countdown(2) - it’ll go to the line
const countArray = countdown(n - 1);
So countArray will be set to what countdown(1) returns, which is just an empty array. We then move on to the line
countArray.unshift(n);
Which adds the number 2 to the array, and finally
return countArray;
should just return [2]… and yet it doesn’t - it returns [2, 1]. Could someone explain what I’m missing?
**Your code so far**
// Only change code below this line
function countdown(n){
if(n < 1){
return [ ];
}else{
const countArray = countdown(n - 1);
countArray.unshift(n);
return countArray;
}
}
console.log(countdown(12))
// Only change code above this line
2
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.125 Safari/537.36
Challenge: Use Recursion to Create a Countdown
Link to the challenge: