Skip to main content
πŸ” Recursion

Countdown

Time to write the function you just traced. Remember the two pieces, and write the base case first:

function countdown(n) {
  if (n <= 0) return [];           // 1. base case: stop
  return [n, ...countdown(n - 1)]; // 2. recursive step: n, then the rest
}
countdown(3); // [3, 2, 1]

The ... (spread) unpacks the smaller array so you get one flat list: [3, ...[2, 1]] becomes [3, 2, 1].

Your task

Write countdown(n) that returns an array [n, n-1, ..., 1]. For n <= 0 return an empty array [].

⚑ 35 XP

🧱 Code blocks

Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.

solution.jsRuns in your browser
Loading editor…
Tests4 to pass
countdown(3) β†’ [3,2,1]
countdown(1) β†’ [1]
countdown(0) β†’ []
countdown(5) β†’ [5,4,3,2,1]

Run your code to check these.