Skip to content

Visualizers

Factorial Recursion Visualizer

Interactive visualization of the recursion call stack for Factorial.

native Client-side
Ready to visualize.

Execution Log

Stack Depth: 0
Result value: -
Current Action:

Idle

Legend:

Active Call (Pushing)
Resolved Frame (Popping)

Factorial Recursion

Factorial of a positive integer $n$, denoted by $n!$, is the product of all positive integers less than or equal to $n$. The recursive formula is $n! = n \times (n-1)!$ with the base case $1! = 1$.

How the Call Stack Works

When a function calls itself recursively, the execution environment allocates a new **stack frame** on top of the program's Call Stack.

  • Pushing (Top-Down phase): The program pushes frames `fact(5)`, `fact(4)`, etc., onto the stack, pausing each caller until the sub-calls return.
  • Base Case: Once `fact(1)` is hit, it returns immediately without further recursive calls.
  • Popping (Bottom-Up phase): The stack frames pop off one-by-one, multiplying the returned value by local variable $n$, passing results back down to resolve the initial caller.

Implementation

function factorial(n) {
  if (n <= 1) return 1; // Base case
  return n * factorial(n - 1); // Recursive case
}