Recursion
Recursion is a technique in which a function calls itself to solve a task, until it reaches a termination condition (a base case).
More simply put:
A function splits a task into subtasks of the same type and solves them by calling itself.
Example - factorial of a number
javascript
function factorial(n) {
if (n === 1) return 1; // base case
return n * factorial(n - 1); // recursive call
}
console.log(factorial(5)); // 120How it works:
javascript
factorial(5)
-> 5 * factorial(4)
-> 5 * 4 * factorial(3)
-> 5 * 4 * 3 * factorial(2)
-> 5 * 4 * 3 * 2 * factorial(1)
-> 5 * 4 * 3 * 2 * 1 = 120The main rule of recursion
- Base case - when the function stops calling itself.
- Recursive call - the step that brings us closer to the base case.
Where it is used
- traversing trees and graphs;
- searching in data structures;
- working with nested structures (for example, the DOM);
- mathematical problems (factorial, Fibonacci numbers, etc.).
In short:
Recursion is when a function solves a task by calling itself, until it reaches a simple base case, after which it returns the result.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.