At what point is the array created? Shouldn’t a variable for the array be initialized first i.e. const countArray = ? Also if n decreases by 1 each time, where is that new number stored? Clearly it is pushing new values of n as it decreases by 1 but where in the function is it recursive? It seems to be doing some sort of n = n-1 thing to get the rest of the values in the array somewhere in the function but I cannot see an expression for this anywhere? It also says in the code description:
At first, this seems counterintuitive since the value of n
decreases , but the values in the final array are increasing . This happens because the push happens last, after the recursive call has returned. At the point where n
is pushed into the array, countup(n - 1)
has already been evaluated and returned [1, 2, ..., n - 1]
.
Ok, again, where are these new vaues of n stored so they are recalled?
**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(5));
// Only change code above this line
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36
Challenge: Use Recursion to Create a Countdown
Link to the challenge: