HOWTO: Add debug statements to your javascript code


Find yourself inserting alert() calls throughout your javascript to debug your code? Wondering how to efficiently add debug statements that you don’t have to turn on and off all the time by commenting them out individually?

I finally decided to write this simple bit of code that allows you to place debug statements throughout your javascript. Hopefully you’ll find it helpful.

  1. Place this code somewhere in your javascript (I put mine at the top so it’s easy to find.)

    // Turn debugging messages on? ["true"|""]
    var debug = "";

  2. Wherever you want a debug statement to pop up (my prefered method in javascript), simply add this line of code:

    (debug) ? alert('DEBUG (insert helpful debug message here)') : "" ;

  3. That’s it. Now, if you set var debug = "true" you’ll get your helpful debug statements popping up all throughout your application. If you set it to null or empty they won’t pop up. Simple, eh? 🙂
, ,

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

sell diamonds