Debugging with console.log

There is one more thing to discuss before we explore bigger and better things beyond “Hello World!” In this book, we have implemented a very simple debugging methodology using the console.log functionality of modern web browsers. This function lets you log text messages to the JavaScript console to help find problems (or opportunities!) with your code. Any browser that has a JavaScript console (Chrome, Opera, Safari, Firefox with Firebug installed) can make use of console.log. However, browsers without console.log support throw a nasty error.

To handle this error, we use a wrapper around console.log that makes the call only if the function is supported. The wrapper creates a class named Debugger and then creates a static function named Debugger.log that can be called from anywhere in your code, like this:

Debugger.log("Drawing Canvas");

Here is the code for the console.log() functionality:

var Debugger = function () { };
Debugger.log = function (message) {
   try {
      console.log(message);
   } catch (exception) {
      return;
   }
}

Get HTML5 Canvas, 2nd Edition 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.