Coding with Jesse

Using Hash for JavaScript Debugging

September 26th, 2007

No, I don't recommend smoking hash before doing your JavaScript debugging :) But I did figure out a technique which you can use to switch a page in and out of debugging mode.

What happens if you need to debug a site that's getting traffic, and you don't want everyone getting your alert() messages or whatever else you need to debug?

Well why not check location.hash and look for a special keyword:

function debug_mode() {
    return location.hash == '#debug';

if (debug_mode()) {
    alert('We are in debug mode!');

Now you can just add #debug to the URL (and hit enter) to turn on debug mode, or just drop the #debug to turn it off. You can even have more than one special "mode" and use different hash values to switch between these modes.

Interested in web development? Subscribe to my newsletter!


1 . Volker at 2007-09-27T09:50:37.000Z


If you're developing with Firebug, the following code gives you another nice opportunity for debugging:

try { console.log("foo"); } catch(err) {}

...will only log in the Firebug console, if the browser knows the function. So your users won't see it, either does the evil IE.

2 . Jesse Skinner at 2007-09-27T10:05:33.000Z

Jesse Skinner

Good point, Volker. I often add a chunk of code when I'm working just in case I forget a few console.log's:

if (!window.console) {
window.console = {
log: function(){}

But I needed to come up with the hash technique to debug some JavaSscript in Internet Explorer on a live site.

3 . Binny V A at 2007-09-27T11:02:13.000Z

Binny V A

Thanks for the tip - I have used '?debug=true' to show debug messages in PHP and server side. So I am going to do something like this...
function debug_mode() {
return document.location.href.match(/debug/);

4 . Tom at 2007-09-28T15:52:33.000Z


Sorry to disappoint you, but most professional web developers have been using this (or a similar) technique for years.

5 . jeanmarie at 2007-10-02T08:46:04.000Z


Thx for this useful comment. I was not aware of this dusty technique, because i'm a lame newbie.

6 . hu dongsheng at 2007-11-14T04:15:07.000Z

hu dongsheng

Thanks. I like Javascript.

7 . grayger at 2008-03-28T15:58:35.000Z


Thanks for the tip. Using window.console in FF also looks good.