Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Understanding how to throw errors is just one part of the equation; understanding when to throw errors is the other. Because JavaScript doesn’t have type or argument checking, a lot of developers incorrectly assume that they should implement these types of checking for every function. Doing so is impractical and can adversely affect the script’s overall performance. Consider this function, which tries to implement overly aggressive type checking:
// Bad: Too much error checking
function addClass(element, className) {
if (!element || typeof element.className != "string") {
throw new Error("addClass(): First argument must be a DOM element.");
}
if (typeof className != "string") {
throw new Error("addClass(): Second argument must be a string.");
}
element.className += " " + className;
}