DSA Trainer
← Foundations

Foundations · Unit 6

Recursion

Recursion is the thing that makes people feel like they are bad at this. A function that calls itself sounds circular, like a definition that uses the word it is defining. Where does it stop? Why does it not loop forever? It feels like magic, and magic is hard to trust.

Here is the reframe that makes it click: recursion is just solving a big problem by solving a slightly smaller version of the same problem, and trusting that the smaller version works. You keep handing off a smaller piece until the piece is so small the answer is obvious. That obvious smallest case is where it stops.

Every recursive function is built from exactly two parts: a base case that says when to stop, and a recursive case that shrinks the problem and calls itself. Once you can spot those two parts, recursion stops being magic and becomes a checklist. This unit builds that checklist one piece at a time.

Goal: Read and write a simple recursive function by naming its base case and recursive case, and trace how the call stack unwinds.
Lesson 1 of 60%

You’re not signed in. Your progress here won’t be saved.

A function that calls itself

Recursion is when a function solves its problem by calling itself on a smaller piece of that problem. That is the whole definition.

Think of a countdown. To count down from 3, you say "3" and then count down from 2. To count down from 2, you say "2" and then count down from 1. Each step does a tiny bit of work and hands the rest to a smaller version of itself. The function that prints the countdown literally calls the same function again with a smaller number.

What makes a function recursive?

function countdown(n) {
  if (n === 0) return
  console.log(n)
  countdown(n - 1)
}
Premium practice

The drills and graded test are premium

The lessons above are free. The interactive practice that turns recognizing the pattern into recalling it on a blank page unlocks with premium:

  • 2 applied drills: train spotting when the concept applies
  • A 5-question graded test to clear the unit
  • The full guided problem ladder with faded hints, plus the cold-read capstone
Unlock everything →

From $6/month. Cancel anytime.