Uncaught RangeError: Maximum Call Stack in JavaScript
Anyone who's worked with JavaScript knows its error reporting can be painfully vague. In this post, we go over a ways to prevent JS errors.
Join the DZone community and get the full member experience.
Join For FreeErrors occur where you least expect them, JS developers face this nemesis on a daily basis.
There are two ways to get these wonderful error messages:
1) Non-Terminating Recursive Functions
Browsers allocate memory to all data types. Sometimes calling a recursive function over and over again causes the browser to send you this message as the memory that can be allocated for your use is not unlimited.
There is nothing more painful for a coder than a non-terminating function or a method of recursion that tends to get stuck in an infinite loop.
Be thoughtful while calling functions and use dry runs to prevent infinite loops.
Maximum call stack gets overflow and washes away your hopes of running the code correctly.
var a = new Array(4294967295); //OK
var b = new Array(-1); //range error
var num = 2.555555;
document.writeln(num.toExponential(4)); //OK
document.writeln(num.toExponential(-2)); //range error!
num = 2.9999;
document.writeln(num.toFixed(2)); //OK
document.writeln(num.toFixed(25)); //range error!
num = 2.3456;
document.writeln(num.toPrecision(1)); //OK
document.writeln(num.toPrecision(22)); //range error!
2) Out of Range
If someone asks you what your name is, you won’t reply ‘2000 yrs.’
var num = 1;
try {
num.toPrecision(500); //no can't have 500 significant digits
}
catch(err) {
document.getElementById("mylife").innerHTML =err.name;
}
Certain functions in JavaScript have ranges of inputs that you can give. Always be careful with these ranges. Sometimes while coding we use functions that, in the end, go out of range while performing tasks. These errors can be easily tackled if you keep track of the ranges of variable types used.
While browsers like Chrome will give error notifications, IE will crash.
It should be a priority to check the valid input ranges.
Examples:
Number.toFixed(digits) 0 to 20
Number.toPrecision(digits) 1 to 21
Number.toExponential(digits) 0 to 20
Null is not 0
Hopefully, this blog will help coders a bit.
If you've experienced these types of errors, leave a comment and tell us how you got around them!
Published at DZone with permission of Robin Jangu. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments