Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Recursion

Recursion means a function calls itself, directly or indirectly. A base case ends the computation, while each recursive step should move the input closer to that case.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}

Recursion (recursion) is a technique in which a function calls itself directly or through other functions. It is not a separate JavaScript keyword or API: it uses ordinary function calls.

A correct solution needs a base case that returns a result without another call and a recursive step that reduces the problem. In the usage example, factorial first validates its argument value: it throws a RangeError if !Number.isInteger(value) || value < 0 || value > 170. After validation, value <= 1 covers both 0 and 1. The function returns 1 for either value; otherwise, it computes value * factorial(value - 1).

Each active call has its own parameters and execution state. Once the deeper call produces its result, execution returns to the pending multiplication. Consequently, factorial(5) produces 120.

An unreachable base case or excessive depth can exhaust call-stack resources; the specification defines no universal safe depth. For very deep data, consider a loop with an explicit stack. The factorial computation itself uses only ECMAScript features. To display the result, the example calls console.log, which is provided by the host environment and is not guaranteed by ECMAScript.

Examples

function factorial(value) {
  if (!Number.isInteger(value) || value < 0 || value > 170) throw new RangeError("integer from 0 to 170 required");
  return value <= 1 ? 1 : value * factorial(value - 1);
}

console.log(factorial(5));

Result

120

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources