0
0
Javascriptprogramming~5 mins

Stack overflow concept in Javascript

Choose your learning style9 modes available
Introduction

A stack overflow happens when a program uses more space in the call stack than it has. This usually occurs because of too many nested function calls.

When you want to understand why a program crashes with a 'stack overflow' error.
When debugging recursive functions that might call themselves too many times.
When learning how computer memory works for function calls.
When optimizing code to avoid too deep or infinite recursion.
When designing algorithms that use recursion and need to be safe.
Syntax
Javascript
function recursiveFunction(count) {
  if (count <= 0) {
    return 'Done';
  }
  return recursiveFunction(count - 1);
}

// Calling with a very large number may cause stack overflow
recursiveFunction(1000000);

This example shows a simple recursive function that calls itself.

If the number is too large, the program runs out of stack space and crashes.

Examples
Small count works fine and prints 'Done'.
Javascript
function recursiveFunction(count) {
  if (count <= 0) {
    return 'Done';
  }
  return recursiveFunction(count - 1);
}

console.log(recursiveFunction(3));
Zero count returns immediately without recursion.
Javascript
function recursiveFunction(count) {
  if (count <= 0) {
    return 'Done';
  }
  return recursiveFunction(count - 1);
}

console.log(recursiveFunction(0));
Missing base case causes infinite recursion and stack overflow.
Javascript
function recursiveFunction(count) {
  // No base case causes infinite recursion
  return recursiveFunction(count);
}

// This will cause stack overflow immediately
recursiveFunction(1);
Sample Program

This program shows a safe recursive call with count 5, which works fine.

Then it tries a very large count that causes a stack overflow error, caught and printed.

Javascript
function recursiveFunction(count) {
  if (count <= 0) {
    return 'Done';
  }
  return recursiveFunction(count - 1);
}

console.log('Calling with count = 5');
console.log(recursiveFunction(5));

console.log('Calling with count = 1000000 (may cause stack overflow)');
try {
  recursiveFunction(1000000);
} catch (error) {
  console.log('Error:', error.message);
}
OutputSuccess
Important Notes

Time complexity depends on the number of recursive calls, here O(n).

Space complexity is also O(n) because each call uses stack space.

Common mistake: forgetting the base case causes infinite recursion and stack overflow.

Use iteration or tail recursion optimization to avoid stack overflow if possible.

Summary

Stack overflow happens when too many function calls use up the call stack memory.

Recursive functions need a base case to stop calling themselves.

Large or infinite recursion causes stack overflow errors.