A recursive function is a function that calls itself. That sounds circular, but each call works on a smaller version of the problem, and the smallest versions are answered directly. It's how you'd explain a factorial in words: 4! is 4 times 3!, and 3! is 3 times 2!, and so on down to 1! = 1, which you just know.
factorial(1) is 1. Without a base case the calls never stop.factorial(n) = n × factorial(n − 1). Each call must move closer to the base case.Each call waits for the one it made; the answers come back in reverse order.
function factorial(n) { if (n <= 1) return 1; // base case: no more calls return n * factorial(n - 1); // pauses here until the inner call returns} factorial(4);Time O(n) — one call per number. Space O(n) — the calls wait on top of each other until the base case answers (the next lesson shows exactly where that memory goes).
sumDigits(n) returns the sum of n's digits."n follow from the answer for something smaller? The digits of 1234 are the digits of 123, plus 4.sumDigits(123) already works; don't trace it in your head. If the base case is right and every call gets smaller, it works.function sumDigits(n) { if (n < 10) return n; // one digit: it is its own sum return sumDigits(Math.floor(n / 10)) + (n % 10); // the other digits, plus the last one}Every recursive function can be written as a loop, and loops are usually a little faster. But many problems are naturally recursive — trees, nested brackets, "try every way" searches, divide-and-conquer sorts — and the recursive code is shorter and closer to how you'd describe the solution. Backtracking, tree traversals, merge sort, quick sort and most dynamic programming start as recursion.
factorial(-1) with a base case of n == 1 calls forever, until the program crashes with a stack overflow.f(n) from f(n) again, or shrinking by the wrong amount and jumping past the base case.factorial(n - 1) without using its result.Was this helpful?