What is recursion in JavaScript?
JavaScriptThe short answer
Recursion is when a function calls itself to solve a problem by breaking it down into smaller, identical subproblems. Every recursive function needs a base case (when to stop) and a recursive case (when to call itself again). Without a base case, the function calls itself forever and crashes with a stack overflow.
A simple example
function countdown(n) { if (n <= 0) { console.log('Done!'); return; // base case — stop here } console.log(n); countdown(n - 1); // recursive case — call itself with a smaller number}countdown(3);// 3// 2// 1// Done!Each call brings n closer to 0. When n reaches 0, the function stops.
Classic example: factorial
function factorial(n) { if (n <= 1) return 1; // base case return n * factorial(n - 1); // recursive case}factorial(5); // 5 * 4 * 3 * 2 * 1 = 120Here is what happens step by step:
factorial(5) = 5 * factorial(4)factorial(4) = 4 * factorial(3)factorial(3) = 3 * factorial(2)factorial(2) = 2 * factorial(1)factorial(1) = 1 ← base case, start returningPractical example: flatten a nested array
function flatten(arr) { const result = []; for (const item of arr) { if (Array.isArray(item)) { result.push(...flatten(item)); // recurse into nested arrays } else { result.push(item); } } return result;}flatten([1, [2, [3, [4]]], 5]); // [1, 2, 3, 4, 5]Practical example: traverse a DOM tree
function getAllTextNodes(element) { const texts = []; for (const child of element.childNodes) { if (child.nodeType === Node.TEXT_NODE) { texts.push(child.textContent.trim()); } else { texts.push(...getAllTextNodes(child)); // recurse into child elements } } return texts.filter(Boolean);}Recursion vs iteration
Most recursive solutions can also be written with loops. Use recursion when:
- The data structure is naturally recursive (trees, nested objects)
- The recursive solution is clearer and easier to understand
- The depth is not too large (JavaScript has a call stack limit)
Use iteration when:
- Performance matters (iteration is faster, no call stack overhead)
- The depth could be very large (risk of stack overflow)
Common Pitfalls
JavaScript does not optimize tail recursion in practice (despite it being in the ES6 spec). Deep recursion can cause a "Maximum call stack size exceeded" error. For very deep structures, consider converting to an iterative approach with an explicit stack.
Interview Tip
Show the factorial example for the concept, then a practical example like flattening an array or traversing a tree. Always mention the base case — forgetting it is the most common recursion mistake. If you can mention the stack overflow risk, that shows you think about edge cases.
Why interviewers ask this
Recursion is fundamental to working with tree structures (DOM, file systems, nested data). Interviewers want to see if you can break problems into subproblems, identify the base case, and write clean recursive code.