Use Recursion to Create a Countdown, Solution 4

Hi everyone, this is my first post, happy to be here at freecodecamp, awesome site!
After doing some forum searching, I am slowing wrapping my head around recursion, but solution 4 is the closest thing to coding black magic since 0x5F3759DF.
To recap, the solution is:

function countdown(n){
   return n < 1 ? [] : [n, ...countdown(n - 1)];

Could someone please explain this, especially the effect of the ellipses?
Thank you!

Welcome, mathias.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


Are you familiar with ternaries?

n < 1 ? [] : [n, ... countdown(n - 1)]

is a ternary expression that will evaluate to [] when n < 1 or [n, ...countdown(n - 1)] otherwise.

The syntax

[n, ...countdown(n - 1)]

builds an array that starts with n and contains the spread contents of countdown(n - 1).

The rest of the logic is the same as the examples with the if statement and multiple return statements.

1 Like

In terms of wrapping your head around recurrsion, the topic was discussed at length here: Replace Loops using Recursion -1 explanation

The use of the ellipses is found in this lesson:

I hope these links help somewhat. If not, feel free to ask for clarification on anything.

1 Like

Hi Jeremy,

I am as yet unfamiliar with ternaries, but will investigate further, along with spread contents (I hope that is what I google).
EDIT: Actually the ternary was fine, I just didn’t recall ‘?’ being called that :slight_smile:

Thanks for the speedy reply.

1 Like

Hi Sky,

Thanks for the syntax correction for code.

The linked articles explained each issue perfectly.

1 Like