Tell us what’s happening:
Why do we use unshift here? Your code so far
// Only change code below this line
function countdown(n){
if (n<1){
return [];
}
else {
countdownArr=countdown(n-1);
countdownArr.unshift(n);
return countdownArr;
}
}
console.log(countdown(10));
var countdownArr=[]
// Only change code above this line
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Use Recursion to Create a Countdown
I believe i might have answered my own question. When running this code through a given number, I, for some reason envisioned it being a literal countdown, but it runs from one, with ‘n’ being the FINAL number. Hence, .unshift returns the last number first in the Arr.
.unshift() appends value to the beginning of the array (unlike .push() which appends to the end). Remember that the recursion, as written here, runs through the entire sequence from n to 1 first before appending anything to your countdownArr. Because all n-1 has already been evaluated before the appending, the appending happens in reverse order of the evaluation. Thus, .unshift() produces an array in descending order.