Hey all,
I’ve just started learning JS. I don’t understand how parts of the code in this lesson about recursion works: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown
I’ve read through the hints and also other posts on the forum, but I still don’t understand parts of the code and what happens when it is executed. This is the code:
function countup(n) {
if (n < 1) {
return [ ];
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
And my questions:
Question 1: I don’t understand what happens when control has reached „countArray.push(n);“ I wonder where n is pushed to because there is no array existing yet.
Question 2: Also I wonder what this function returns (line7) concretely after the first loop when n is e.g. 5. Is it „countup(4)“? I don’t think that this is correct.
Question 3:
What happens when n reaches a value of 0 – I think the code „return []
;“ is executed so an empty array is returned. But this is obviously wrong. What am I missing?
I will be so happy as soon as I’ve understood this. I would be very happy if yomebody could help me.
Regards,
Alex