I'm currently working through freeCodeCamp's JS course.
One of the last problems asks you to create a recursive function that only accepts one argument n
and creates an array that counts down from n
to 1.
I was able to solve the problem using this code (SPOILERS IF YOU ARE ALSO WORKING ON THIS PROBLEM):
// Only change code below this line
function countdown(n) {
if (n < 1) {
return [];
} else {
const countArray = countdown(n - 1);
countArray.unshift(n);
return countArray;
}
}
// Only change code above this line
// my test
console.log(countdown(1))
I mostly arrived at this answer by copying syntax in the provided example. I plugged my answer into Python Tutor's code visualizer here. I will be referencing the steps in this visualizer.
Question about step 3: I notice it says countArray
(block 1) is undefined. I assume this is because the function is hanging onto n
and will go back and populate the array once the base statement creates it? Does this mean the defining of the array is delayed until the base case is reached?
Question on step 6: I see that my code worked as intended and now that n
is 0, the base case is activated and the function returns an empty array. How does the code know that I want to populate this empty array with countArray
? What ties the two together.
Question on step 7: If you can only answer one of my questions, I would like it to be this one.: Why does the function continue at all after the base case was reached (when n = 0)? From my flawed understanding return
ends the function immediately. By this logic, my code shouldn't do what is intended. It would always count n
down, and then regardless return an empty array.
Thank you for reading my question. If my thoughts are not detailed clearly enough here, please let me know how I can clarify.