Solving a problem by having a function call itself on smaller versions of the same problem.
A recursive function breaks a problem into smaller copies of itself, and stops at a base case that can be answered directly. Every recursive call goes on the call stack, so depth costs memory. Any recursion can be rewritten with an explicit stack or a loop, but for trees, divide-and-conquer, and backtracking, the recursive form is usually the clearest.
Step through recursion live, one move at a time β this becomes a fully interactive visualizer.
Coming soonn in terms of a smaller input.n costs O(n) memory.function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
// factorial(4)
// = 4 * factorial(3)
// = 4 * 3 * factorial(2)
// = 4 * 3 * 2 * factorial(1)
// = 4 * 3 * 2 * 1 = 24Usually a little, because each call pays function-call overhead and stack space. But for naturally recursive structures (trees, nested data, divide-and-conquer) the clarity is worth it, and the asymptotic complexity is the same.
A recursive call that is the very last operation in the function. Some languages optimize it into a loop (tail-call optimization), eliminating stack growth β but JavaScript engines generally do not, so don't rely on it there.
Print the arguments (with indentation by depth), verify the base case fires, and test the smallest inputs first: if f(0) and f(1) are right and f(n) correctly uses f(nβ1), induction does the rest.
Share what clicked for you and see notes from other learners on this topic.
Coming soon