How To: Stackoverflow in Javascript
by Matei Oprea
What’s a stackoverflow, anyway?
Well, stackoverflow occurs when a program attempts to use more memory than is available on the call stack. Every program has a limited amount of memory that it can use (seems pretty fair, right?).
I worked for a year and a half with Javascript / DOM Modifications at OKAPI. Thinking of 2-3 methods for overflowing the stack in javascript will be easy :). Hehe.
If you declare a function in global scope this may hurt you a little bit. Let’s say you’re working on a function called “open”, which will open the door to your site (jk – another url).
var open = function(url) {
window.open(url);
//We do log this :)
console.log("Yay! I opened the url");
}
Great. You’re a great developer. Ok, you’re not. If you later decide to use window.open() native function, you’re gonna have a bad time. Why? Because a function defined in the global scope can be called in two ways (let’s write a function which will console log a message):
var dummyFn = function () {
console.log("You are awesome");
}
Calling the function:
1.
dummyFn();
2.
window.dummyFn();
I think that you understand right now that we created a circular reference, right? This will result in a stackoverflow which will kill your browser (use it on your own risk).
Uncaught RangeError: Maximum call stack size exceeded
We can create a stackoverflow by calling a function inside her body, too:
var foo = function() {
foo();
}
Calling
foo()
right now will result in a stackoverflow. But how about a large codebase, when two functions call each other:
var first = function () {
second();
};
var second = function () {
first();
}
first();
Well, it’s pretty obvious that this will result in a stackoverflow too. Hopefully the browser will stop the execution of your code and display an error. You can always use try-catch statement to catch this type of errors.













