Skip to main content

Recursion

Recursion is a technique in which a function calls itself to solve a task, until it reaches a termination condition (a base case).

More simply put:

A function splits a task into subtasks of the same type and solves them by calling itself.


Example - factorial of a number

javascript
function factorial(n) { if (n === 1) return 1; // base case return n * factorial(n - 1); // recursive call } console.log(factorial(5)); // 120

How it works:

javascript
factorial(5) -> 5 * factorial(4) -> 5 * 4 * factorial(3) -> 5 * 4 * 3 * factorial(2) -> 5 * 4 * 3 * 2 * factorial(1) -> 5 * 4 * 3 * 2 * 1 = 120

The main rule of recursion

  1. Base case - when the function stops calling itself.
  2. Recursive call - the step that brings us closer to the base case.

Where it is used

  • traversing trees and graphs;
  • searching in data structures;
  • working with nested structures (for example, the DOM);
  • mathematical problems (factorial, Fibonacci numbers, etc.).

In short:

Recursion is when a function solves a task by calling itself, until it reaches a simple base case, after which it returns the result.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.