JSVerse
Advanced JavaScript / Recursion

Recursion

A function that calls itself, each call a step closer to a base case.

Recursion solves a problem by breaking it into a smaller version of the same problem, calling itself with that smaller input, until it hits a base case simple enough to answer directly. Every recursive call pushes a new frame onto the call stack, exactly like any other function call. Once the base case returns, the stack unwinds — each pending call resumes and multiplies its own result by the value it was waiting on.

Codeeditable — Run executes your edits
Loading...
Console
Output will appear here
Visualization
Call Stack
Nothing on the stack
↑ most recent call on top
Why?

factorial(1) is the base case and returns first. Then each paused call multiplies its own n by the result it was waiting for, unwinding back down to factorial(5).