How to Use Recursion in JavaScript: Simple Guide and Examples
In JavaScript,
recursion means a function calls itself to solve smaller parts of a problem. You define a base case to stop the calls and a recursive case to continue calling the function with simpler inputs.Syntax
A recursive function in JavaScript calls itself inside its body. It must have a base case to stop the recursion and a recursive case to continue calling itself with simpler arguments.
function functionName(params) {}: Defines the function.if (base condition) return value;: Stops recursion.return functionName(simpler params);: Calls itself with simpler input.
javascript
function recursiveFunction(param) { if (param <= 0) { return 'Done'; // base case } return recursiveFunction(param - 1); // recursive case }
Example
This example shows a function that counts down from a number to zero using recursion. It prints each number and stops when it reaches zero.
javascript
function countdown(n) { if (n <= 0) { console.log('Blast off!'); return; } console.log(n); countdown(n - 1); } countdown(5);
Output
5
4
3
2
1
Blast off!
Common Pitfalls
Common mistakes when using recursion include:
- Missing or incorrect base case causing infinite recursion and crashing the program.
- Not simplifying the input in the recursive call, so the function never reaches the base case.
- Using recursion for very large inputs without optimization, which can cause stack overflow errors.
javascript
function wrongRecursion(n) { // Missing base case console.log(n); wrongRecursion(n - 1); } // Corrected version function correctRecursion(n) { if (n <= 0) return; console.log(n); correctRecursion(n - 1); }
Quick Reference
- Always define a base case to stop recursion.
- Make sure each recursive call moves closer to the base case.
- Use recursion for problems that can be broken into smaller similar problems.
- Test with small inputs first to avoid infinite loops.
Key Takeaways
Recursion is a function calling itself with simpler inputs until a base case stops it.
Always include a base case to prevent infinite recursion and crashes.
Each recursive call must progress toward the base case by simplifying input.
Recursion is useful for problems like counting, searching, and tree traversal.
Test recursive functions with small inputs to ensure correctness and avoid errors.