See dedicated page about recursion.
What is recursion
It’s just a fancy word for a function calling itself. Simplest useless example:
// Note: this will quickly crash
function infiniteLoop() {
infiniteLoop();
}
Why use it?
It can be a valuable technique to break down a problem space into smaller (similar) problems. Canonical examples used for demonstration purposes are computing fibinacci numbers and Tower of Hanoi game.
Key attributes for it to be useful:
- Ability to incrementally break down the input into a smaller sub-problem.
- Base condition is needed to stop the recursion when it has reached its simpliest form.
That being said, it is rarely used in actual production code because it is typically worthwhile to instead rewrite it to be iterative for better space and time complexity. It is most frequently used for interview questions which test a candidate’s ability to breakdown a big problem into smaller sub-problems (an arguably valuable skill, but somewhat independent of an actual need for recursion). It is typical for a candidate to initially solve an interview problem with recursion (simpler to write and requires few lines of code) and then as a phase two, rewrite it as an iterative solution.
It is a mathmatically proven fact that every recursive solution can instead be implemented as an interative solution.
Common pitfalls
If your base case can never be achieved, then you will have an infinite loop and have a stack overflow. A stack overflow is an error scenario where your callstack exceeds the available memory for function call depth.