Chapter 10. Debugging and Logging

Historically, debugging JavaScript in a web browser has been a challenge because of the lack of a standard output for debugging information. As a result, many JavaScript developers start out by using alert() to pop up debugging messages, which quickly becomes catastrophic if the alert() is inadvertently placed in an infinite loop. (For exactly this reason, Google Chrome has the decency to offer the option to disable future alert messages from a page if too many appear in succession.)

To address this limitation, newer browsers have begun to offer the following API for logging information to a separate window or pane:

console.log('This is some debugging information.');

If console.log() gets called in an infinite loop, at least the user has a chance to close the page before the browser locks up completely. Although this is an improvement, it is not an option on older browsers. More importantly, when working on a large JavaScript codebase, it helps to have a more customizable logging API so that logging options for different modules can be set independently. Fortunately, the goog.debug package in the Closure Library has various options for logging debugging information and recording JavaScript errors, so it should provide the flexibility that you need.

Although a JavaScript debugger, such as Firebug, is often the best tool to use when debugging code, it is not always a practical option. For example, if there is an error that occurs in an event handler for ...

Get Closure: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.