Tell us what’s happening:
Code works fine. There are no problems with execution or whatsoever.
I just cannot understand how this recursion works, on this block:
else {
const countArray = countdown(n - 1);
console.log(`n: ${n}, countArray ${countArray}`);
countArray.unshift(n);
return countArray;
The first line that is getting executed is:
const countArray = countdown (n - 1);
which as far as I can tell this the point that the variable recalls the function and as I far as I know, when you use const (constant) you cannot change the variable type.
but still the program continues to the next line where it pushes the next value to the array and after pushing the value the next line is return countArray.
- Why doesn’t the function stop at the return?
- How it continues after the return and still pushes values?
- How does it return the full array?
- How does the program/function know how many times the recursion should run?
Is that a feature of Javascript or programming?
Does Javascript have for example, recursion detection?
Your code so far
//Only change code below this line
function countdown(n){
if (n < 1 ) {
return [];
} else {
const countArray = countdown(n - 1);
console.log(`n: ${n}, countArray ${countArray}`);
countArray.unshift(n);
return countArray;
}
}
console.log(countdown(5)); // [5, 4, 3, 2, 1]
console.log(countdown(10));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
.
Challenge: Use Recursion to Create a Countdown
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown