Tell us what’s happening:
In this exercise example,
function countup(n) {
if (n < 1) {
return [];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
The numbers are in ascending order.
The solution is however is in descending order. the unshift(n) happens only after the recursive function has called itself upto 4 to 1, and then we add 5 in the beginning. That makes sense. The example didn’t make sense to me how the numbers were arranged from small to large?
Your code so far
function countdown(n){
if (n < 1) {
return [];
} else {
var myCount = countdown(n - 1);
myCount.unshift(n);
return myCount;
}
}
```js
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36
.
Challenge: Use Recursion to Create a Countdown
Link to the challenge: