Tell us what’s happening:
I know how the recursion functions structured but I am not understanding how the .push() method is excuted after ‘recursive call has finished’ please help me
**Your code so far**
// Only change code below this line
function countdown(n){
if(n<1){
return [];
}else{
let result = countdown(n-1);
result.unshift(n);
console.log(result);
return result;
}
}
// Only change code above this line
**Your browser information:**
User Agent is: Mozilla/5.0 (Linux; Android 10; TECNO B1g) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.82 Mobile Safari/537.36
For countdown(5), n is not < 1, so the else block is executed. In it, it’s needed to calculate countdown(4).
For countdown(4), n is not < 1, so the else block is executed. In it, it’s needed to calculate countdown(3).
This going deeper into the recursive calls happens until countdown(0) is called from countdown(1), for which base case is entered, and [] returned.
Now the previous recursive calls can continue in reverse order.
In the countdown(1), result is now []. So result.unshift(n) will unshift1 into the result array. Finally countdown(1) returns [1].
In the countdown(2), result is now [1]. So result.unshift(n) will unshift2 into the result array. Finally countdown(2) returns [2, 1].
This continues until the first recursive call is reached again. Where for countdown(5), result will be [4, 3, 2, 1] and 5 is unshifted into the array, resulting in final answer [5, 4, 3, 2 ,1].