Stack overflow concept in Javascript - Time & Space Complexity
When a program runs, it uses a special memory area called the call stack to keep track of function calls.
We want to understand how the number of function calls affects the program's running steps and memory use.
Analyze the time complexity of the following recursive function that calls itself without a stopping condition.
function infiniteRecursion() {
return infiniteRecursion();
}
infiniteRecursion();
This code calls the same function again and again without stopping, causing the call stack to grow endlessly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive function calls without end.
- How many times: Infinite times until the program crashes.
Each call adds a new layer to the call stack, growing step by step without stopping.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls stacked |
| 100 | 100 calls stacked |
| 1000 | 1000 calls stacked |
Pattern observation: The number of calls grows directly with input, but here input is the depth of calls, which never ends.
Time Complexity: O(n)
This means the number of steps grows directly with the number of recursive calls before the program crashes.
[X] Wrong: "The recursion will stop on its own without a base case."
[OK] Correct: Without a stopping point, the function keeps calling itself forever, causing the program to crash with a stack overflow.
Understanding how recursive calls use the call stack helps you write safe functions and avoid crashes in real projects.
"What if we add a base case to stop the recursion after a certain number of calls? How would the time complexity change?"