Explore console.log if you use JavaScript alert extensively for debugging

The JavaScript alert method is something that most web developers use to debug their code. However, now with all popular browsers incorporating Developer tools within them, there are easier ways to debug client-side code. Firebug is an optional add-on for Firefox that adds richer features to those natively available & probably the motivator for browsers to develop their own Developer tools. I guess, it was IE that started using F12 as keyboard shortcut to start up Developer tools and now that's synonymous with Developer tools on almost all browsers.


Within the Developer tools, a Console panel exists for executing script statements on-the-fly. You can make use of Console methods to expose information that is flowing through your scripts. The console.log method can be used as an alternative to the obtrusive JavaScript alert method to track what's going on within your code without having to click OK for every dialog box that alert throws up. This will work only if you have the Console opened though.


So to remove your debugging code when you deploy to production, use this:
if ( window.console ) {
  // console is available
}


While console.log is one of the more common methods supported in popular browsers(IE, Firefox Firebug, Chrome, Safari), there are other methods as well for which support may vary -


  • console.info
  • console.warn
  • console.error
  • console.assert


Ctrl+Shift+J shortcut lets you jump to the Console panel in Chrome.

Comments