Why doesnt countdown(2) just return 2?

Tell us what’s happening:

I’ve completed the challenge just fine, I just don’t get how the recursion works (and yes, I’ve read some articles on it, which is why I’m asking)

So here’s how I understand it. If I run countdown(2) - it’ll go to the line

  const countArray = countdown(n - 1);

So countArray will be set to what countdown(1) returns, which is just an empty array. We then move on to the line

  countArray.unshift(n);

Which adds the number 2 to the array, and finally

return countArray;

should just return [2]… and yet it doesn’t - it returns [2, 1]. Could someone explain what I’m missing?

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

console.log(countdown(12))

// Only change code above this line

2
  **Your browser information:**

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

Challenge: Use Recursion to Create a Countdown

Link to the challenge:

Is it? Look closely at your code to see when it returns an empty array:

if(n < 1){
return [];
}

P.S. To display your code in here you need to wrap it in triple back ticks. On a line by itself type three back ticks. Then on the first line below the three back ticks paste in your code. Then below your code on a new line type three more back ticks. The back tick on my keyboard is in the upper left just above the Tab key and below the Esc key.

1 Like

Are you sure about that?

Derp. Yeah, I see it now. Thanks.

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