Basic JavaScript - Use Recursion to Create a Countdown

Tell us what’s happening:

Describe your issue in detail here.
I just wanted to say that, this made a lot more sense when I figured out that recursion is synchronous as most of JS. Once I figured out what was happening, it made sense as to why it was happening. I couldn’t for the life of me understand why it wasn’t moving to the next line when I thought it should. Sometimes, I feel as if this course doesn’t tell me some important functionality details.

Your code so far

javascript
// Only change code below this line
function countdown(n){
    if (n < 1) {
        return [];
    }
    else {
        const countArray = countdown(n - 1);
        countArray.unshift(n);
        return countArray;
    }
  }

  //let a = countdown(10);
  console.log(countdown(10));
// 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/120.0.0.0 Safari/537.36

Challenge Information:

Basic JavaScript - Use Recursion to Create a Countdown

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

If I gave you the following code:

let answer = getTheAnswer();
answer += 1;
return answer;

Would you think that the line answer += 1 should run before the function getTheAnswer returns a value? I’m guessing you understand that first the function getTheAnswer must be called, and then it must return a value, and only after it returns a value can that value be assigned to the variable answer, and only after that happens can the next line be executed.

This works the same for recursion:

  const countArray = countdown(n - 1);
  countArray.unshift(n);
  return countArray;

Just like in my example, the function countdown must be called and executed and return a value, and only then can that value be assigned to countArray, and then only after that can the next line be executed. Don’t let the fact that it is making a recursive function call fool you. The recursive function call is still a function call, just like getTheAnswer in my example. In both cases, the calling function must pause and wait for the called function to execute and return a value before it can continue on.

1 Like

Your explanation makes sense and helps. For some reason, I think I was thinking that it would iterate through like a for loop until I figured out that it didn’t lol.

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