Skip to content

Stack Overflow

Quick summary

Your program made too many nested function calls — the call stack ran out of space and the program crashed.

Why this happens

  • Recursive function with no base case (infinite recursion)

  • Recursive function where the recursive call does not move toward the base case

  • Very deep recursion that exceeds the stack limit

Minimal example

✗ Broken code
function countdown(n) {
  console.log(n);
  countdown(n - 1); // No base case!
}
countdown(5); // Stack overflow
✓ Fixed code
function countdown(n) {
  if (n < 1) return; // Base case
  console.log(n);
  countdown(n - 1);
}
countdown(5); // 5, 4, 3, 2, 1

Without a base case, countdown calls itself forever, each call adding to the stack until it overflows. Adding if (n < 1) return stops the recursion.

How to diagnose

  • Check if the error message mentions 'Maximum call stack size exceeded'

  • Look for recursive functions and verify they have a reachable base case

  • Count the recursion depth — is it unbounded?

How to fix

  • Add or fix the base case so recursion terminates

  • Ensure each recursive call moves closer to the base case

  • Convert deep recursion to an iterative loop

How to prevent

  • Always include and test the base case in recursive functions

  • Prefer iteration over recursion for simple repetition

Related Resources

Related Glossary

Related Lessons

  • Recursion

    Learn about recursion and base cases.

← Back to language