Recursion inside of a constant

Tell us what’s happening:
I am struggling to understand / follow what is happening in this example with the function inside the const countArray.

When the countup function is called in the initialization of const countArray and begins counting down from n-1, is an array created inside this constant? It must seem so because the next line adds (using push array method) 5 to it.

Is there a way for me to see this happen step by step so I can better understand what is happening under the hood?

I understand everything else that is happening in this example, but I’m stuck on this one part. I cannot picture what is happening in my head. If countArray creates an array using the countup function, would it not look like so: [4,3,2,1]? And if so, when you push n, would the array not look like so: [4,3,2,1,5]?

Your code so far


//Only change code below this line
function countdown(n){
return;
}
console.log(countdown(5)); // [5, 4, 3, 2, 1]

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36.

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

1 Like

Thank you, that site is VERY helpful and I will definitely use it more often.

However, I am still not 100% clear on what is happening during the recursive call to countup.

Are the values for each value of n after calling the respective countup function stored temporarily in these stack frames until n = 0? At which point, countArray.push(n) begins to work back up the stack to populate the empty array?

countup2

1 Like

Thanks RandellDawson! Appreciate your help.