Tell us what’s happening:
Describe your issue in detail here.
I wrote this code without any assistance and it runs perfectly. But i honestly just patterned it after the example in the exercise, by my logic the console.log should be returning the reverse of the countdown i.e 1,2,3,4,5 and i should not be passing this exercise.
Here’s how i see it -
The first " countArray.unshift(n) " adds the intial value of n into the beginning of the array … lets say n = 5.
[5, …]
next time the loop runs " countArray.unshift(n) " should add 4 to the beginning of the array.
[ 4, 5, …]
until we get 1,2,3,4,5 instead i get 5,4,3,2,1 .
can someone dumb down what is happening here for me ?
Your code so far
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 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/103.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Use Recursion to Create a Countdown
Link to the challenge: