Javascript recursion challenge j

Tell us what’s happening:
Describe your issue in detail here.
i cant seem to follow the code where the it calls the its own function countup(n-1). it seems to me it keep calling itself without every going to the next line with the push statement.

  **Your code so far**
  function countup(n) {

if (n < 1) {
return ;
} else {
const countArray = countup(n - 1);
countArray.push(n);
return countArray;
}
}
console.log(countup(5));


// Only change code below this line
function countdown(n){
 if (n < 1) {
  return [];
} else {
  const countArray = countdown(n - 1);
  countArray.switch(n);
return countArray;
}
// Only change code above this line
  **Your browser information:**

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

You’re calling the function with a smaller input, so eventually you will reach the base case.

so im missing something, it will keep calling its own function decrementing the value of n until the value is less than 1 and the function ends without ever seeing the line below the recursion. sorry im trying to make some sense out of this.

Each function call is independent. The function fully runs all the way to a return statement each time you call it.

After the function call returns, then the next two lines run.

so basically once once you call the func countdown calls itself and assignes n-1 to countArray, it goes to the next 2 lines and not call itself again?

No. A function call is a distinct event.

ok so i see it now . you keep calling the function til n=0 . and once it breaks out of the recursion and empy array is assigned to countArray and then the current value of n is pushed into the array, which is one. bujt now im confused how a 2,3 ,4 and 5 is generated. there is no increment before the return.

The function always returns something on EVERY function call.

ok got it. so i take it the values for when n return a 4 3 2 1. dont go away . they are stored in some stack waiting to be used after the recursion is over and an array is returned. thanks alot for the help. sorry if i was being a bother earlier. oh and the switch was meant to be a unshift. i was trying to use the opposite of a push and put the eleme nt in the beginning of the array

It’s no bother er anything like that. Recursion is hard.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.