Recursion and Stack in JavaScript
Recursion is a programming technique where a function calls itself to solve smaller instances of a problem. Each recursive call is stored in the call stack, which helps track execution.
What is Recursion?
A function is recursive if it calls itself within its own body.
Example: Counting Down
🔹 Output:
Understanding the Call Stack
JavaScript uses a call stack to track function calls. Each function call is pushed onto the stack and removed when it returns.
Example: Factorial Calculation
Call Stack Flow for factorial(5)
The last function in the stack executes first (LIFO - Last In, First Out).
Base Case and Infinite Recursion
A base case is needed to stop recursion, or the function will keep calling itself indefinitely, causing a stack overflow.
🚨 Example of Infinite Recursion (❌ BAD)
✅ Always define a base case to stop recursion.
Recursion vs Iteration
Example: Finding the Sum of Numbers
- Recursive Approach
- Iterative Approach
When to Use Recursion?
- Problems that require breaking into smaller subproblems (e.g., trees, graphs, backtracking).
- When iteration would make the code more complex.
Common Recursive Problems
Fibonacci Sequence
Optimization: The recursive Fibonacci approach has O(2ⁿ) complexity, so memoization (caching results) can improve performance.
Tail Recursion (Optimization)
Some languages optimize recursive functions by using tail recursion (where the recursive call is the last operation), but JavaScript does not optimize it well.
Tail Recursive Sum
🎯 Summary
✔ Recursion is when a function calls itself to solve a smaller problem.
✔ Base cases are essential to stop infinite recursion.
✔ Call Stack follows LIFO (Last In, First Out).
✔ Recursion vs Iteration: Use recursion for problems like trees, graphs, and backtracking.
✔ Optimization: Use memoization or tail recursion to improve performance.
🚀 Recursion is a powerful concept, but be cautious about stack overflow! Let me know if you need more examples. 😊