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.
Stack overflow concept in 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.
function recursiveFunction(count) { if (count <= 0) { return 'Done'; } return recursiveFunction(count - 1); } console.log(recursiveFunction(3));
function recursiveFunction(count) { if (count <= 0) { return 'Done'; } return recursiveFunction(count - 1); } console.log(recursiveFunction(0));
function recursiveFunction(count) { // No base case causes infinite recursion return recursiveFunction(count); } // This will cause stack overflow immediately recursiveFunction(1);
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.
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); }
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.
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.