BeginnerCoder

Lesson 20 — Recursion

A function that calls itself

Recursion solves a problem by solving a smaller version of the same problem. It needs a base case — an input small enough to answer directly — or it never stops. Factorial: 5! = 5 × 4 × 3 × 2 × 1, and n! = n × (n-1)!, with 1! = 1 as the base case.

factorial(3) → 3 * factorial(2) → 3 * 2 * factorial(1) → 3 * 2 * 1

Why it matters: nested things — folders, menus, comment threads — are naturally recursive.

Want it another way?
Task

Finish factorial: return 1 when n <= 1, otherwise n * factorial(n - 1).

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with JavaScript Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.