Theory
Recursion is a technique where a function calls itself to solve smaller versions of the same problem. Every recursive solution needs a base case that stops the recursion. Recursion is commonly used with trees, graphs, divide-and-conquer and backtracking.
Example
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5));
Expected Output
120
Practice
Write a recursive function to calculate the sum of numbers from 1 to n.
Interview Questions
- What is recursion?
- What is a base case?
- Why is a base case important?
- Where is recursion commonly used?