Tell us what’s happening:
Below I have the solution text but I am struggling to understand it.
I’m trying to understand the order in which the code executes. As far as I can see, (because we are counting down from n) the very last thing that is happening is the introduction of the square array brackets.
For example, if n=6, we skip the if statement (because n !< 1) and go straight to the else statement that is creating the variable arr and unshifting values into the array that does not yet exist. Only after 6 recursions does the if statement trigger, creating the array.
I know that I am incorrect but I can’t fathom how. Any help would be appreciated aid my understanding of this concept.
Your code so far
// Only change code below this line
function countdown(n) {
if (n < 1) {
return [];
} else {
const arr = countdown(n - 1);
arr.unshift(n);
return arr;
}
}
// Only change code above this line
Your browser information:
User Agent is: Chrome/111.0.0.0
Challenge: Basic JavaScript - Use Recursion to Create a Countdown
Don’t use countdown(6) as an example. Make it easy on yourself and use countdown(1). When n is 1 then you will hit the else statement:
let countArray = countdown(n - 1);
Now remember, the function can’t move on from that line until it gets a value from the recursive call countdown(n - 1). So tell me, what will countArray equal after that recursive call returns?
Thanks for your response. countArray will equal countdown(0), which will return . But once this has been returned in the if statement, how then can the else statement be triggered to unshift the values into the array?