Enabling/Disabling JavaScript Debug Messages Made Easy

Nov 4, 2010 2 min read

Do you remember the days when you had to “alert debug” your JavaScript code? I most certainly do. But thanks to tools like Firebug and Web Inspector, debugging got a lot easier. With tools like these, you do not have to click the OK button over and over again on each alert panel. Instead you can use the console provided by these tools and output debug messages by using functions like console.log() and console.error().

But what if you quickly want to disable all debug messages in all of your JavaScript files in your project at once? Usually, you would search for strings that start with console. and replace them with an empty string. Of course, using find/replace, this is not such an unbearable task. But what if you want to have the debug messages back later? Undo the find/replace for every file in your project? There is an easier way of doing this.

Let’s take a look at some code first:

// Either true for showing debug messages or false for not showing them
const DEBUG = true;

if (DEBUG === false) {
  // An array that holds the name of all console functions that should be disabled
  var consoleMethods = [
    // Common for Firebug and WebKit/Safari
    'log', 'debug', 'info', 'warn', 'error', 'assert', 'clear', 'dir', 'dirxml',
    'trace', 'group', 'groupCollapsed', 'groupEnd', 'time', 'timeEnd', 'profile',
    'profileEnd', 'count', 'exception', 'table',
    // WebKit/Safari specifc
    'markTimeLine'
  ];

  // Overwrite every console function with an empty function
  for (method in consoleMethods) {
    window.console[consoleMethods[method]] = function() { };
  }

  // Add this, if you want to disable alert messages as well
  if (window.alert) {
    window.alert = function() { };
  }
}

What I usually do is, I define a boolean variable (line 2) that I either set to true if I want to show debug messages, or false if I do not want to show them. If this variable is set to false, all functions that I do not want to show any output in the console (defined in lines 6-13) are overwritten by an empty function (lines 16-18), therefore not doing anything when called. Usually, I do not want the alert function to do anything as well, so I overwrite this function, too (lines 21-23).

That’s it, pretty simple, eh?! Hope you find this useful.

References