Recursion is when a function calls itself. This can solve problems that repeat at each step but become simpler. Classic example — calculating factorial of a number. 🔁
A function that calls itself:
function countDown(n) {
if (n <= 0) return;
console.log(n);
countDown(n - 1); // Calling itself
}Recursion is a powerful programming technique where a function calls itself. This might seem strange, but it’s very useful for certain tasks. 😊
A function that calls itself:
function countDown(n) {
if (n <= 0) return;
console.log(n);
countDown(n - 1); // Calling itself
}function factorial(n) {
// Base case — stopping recursion
if (n <= 1) return 1;
// Recursive case
return n * factorial(n - 1);
}// factorial(3) creates stack:
// factorial(3) → 3 * factorial(2)
// factorial(2) → 2 * factorial(1)
// factorial(1) → 1 (base case)function power(base, exponent) {
if (exponent === 0) return 1;
return base * power(base, exponent - 1);
}
console.log(power(2, 3)); // 8 ✅const tree = {
value: 1,
children: [
{ value: 2, children: [] },
{ value: 3, children: [{ value: 4, children: [] }] }
]
};
function sumTree(node) {
let sum = node.value;
for (let child of node.children) {
sum += sumTree(child); // Recursive call
}
return sum;
}function recursive(n) {
// ❌ Without base case — infinite recursion
// return recursive(n); // Stack overflow!
// ✅ With base case
if (n <= 0) return; // Stopping
return recursive(n - 1);
}// Each call takes space in stack
// Too many calls — stack overflow error// Traversing folders and files
function scanDirectory(dir) {
console.log(dir.name);
for (let item of dir.children) {
if (item.isDirectory) {
scanDirectory(item); // Recursive traversal
}
}
}// Quick sort
function quickSort(arr) {
if (arr.length <= 1) return arr;
const pivot = arr[0];
const less = arr.slice(1).filter(x => x <= pivot);
const greater = arr.slice(1).filter(x => x > pivot);
return [...quickSort(less), pivot, ...quickSort(greater)];
}// ❌ Infinite recursion
function bad(n) {
return bad(n - 1); // No stopping!
}
// ✅ With stopping
function good(n) {
if (n <= 0) return; // Base case
return good(n - 1);
}// ❌ May cause stack overflow
function deep(n) {
if (n <= 0) return;
return deep(n - 1);
}
// deep(100000); // Error!
// ✅ Iteration instead of deep recursion
function iterative(n) {
for (let i = n; i > 0; i--) {
// Same thing, but without recursion
}
}Recursion is an elegant way to solve problems that repeat at different levels. But be careful with the base case! ⚠️
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪