Functions Calling Themselves
Recursion is when a function calls itself to solve a smaller part of the same problem.
Example: Factorial
function pow(x, n) {
if (n == 1) return x; // Base of recursion
return x * pow(x, n - 1); // Recursive step
}
Execution Stack
Each function call creates a " frame " in the stack where its variables are stored.
- A large number of nested calls can lead to a Maximum call stack size exceeded error.
Caution
The recursion depth limit in browsers is usually around 10,000. If your task requires more, use a standard loop.
Tip
Recursion makes code incredibly clean when working with tree structures (like a site menu or folders on a disk).