Functions and scope

JavaScript Recursion

Learn how recursion works in JavaScript when a function calls itself, using a factorial function as an example and understanding the call stack along the way.

Recursion means a function calls itself. You need a named function (or a name you can reference) so the body can invoke the same function again.

The classic teaching example is a factorial. The factorial of 4 is 4 * 3 * 2 * 1, which is 24.

function factorial(n) {
  return n >= 1 ? n * factorial(n - 1) : 1
}

factorial(1) //1
factorial(2) //2
factorial(3) //6
factorial(4) //24

The base case is n < 1, which returns 1. Without a base case that stops the calls, recursion never ends.

You can write the same logic with an arrow function:

const factorial = (n) => {
  return n >= 1 ? n * factorial(n - 1) : 1
}

factorial(1) //1
factorial(2) //2
factorial(3) //6
factorial(4) //24

Each call waits for the inner call to finish. JavaScript tracks that chain on the call stack.

Break the step-down and you get infinite recursion:

const factorial = (n) => {
  return n >= 1 ? n * factorial(n) : 1
}

Run it and you will see:

RangeError: Maximum call stack size exceeded

Every function call pushes a frame onto the stack. When the stack fills up, the runtime stops with that error.

Try factorial(4) in the console, then introduce the bug above. The stack trace shows how deep the calls went.

Recursion fits problems defined in terms of smaller versions of the same problem. Tree walks and divide-and-conquer code often start here.

An iterative loop with an explicit stack can replace deep recursion when stack limits matter. Write the recursive version first unless profiling proves you need the loop.

Always define the base case before the recursive call. That is the part that turns infinite self-calls into an answer.

Run factorial(4) and read the returned number before you try the broken version that forgets to decrement.

Each recursive call adds a stack frame until the base case returns. That is the mechanism the RangeError message refers to.

Lesson completed