The Three Ways of Setting Breakpoints in JavaScript

There are at least three ways to set breakpoints against JavaScript running in the browser.

1) Use Chrome’s developer tools or Firebug to locate the line of JavaScript, then set the breakpoint with the mouse.

To do it in Chrome, first open the developer tools (Ctl + Shift + I), or go to the wrench menu, Tools, Developer Tools.

  1. Select the Scripts tab.
  2. Click the little folder icon on the far left.
  3. Navigate to the source file where you want to set the break point.
  4. Find the line in question, then click the line number to set the breakpoint (a little highlighted triangle will appear).
  5. When the breakpoint is fired, you get access to the watches section where you can run arbitrary expressions, see all the variables in scope, and the call stack. Sweet!

Chrome dev tools set breakpoint

 

2) Use the ‘debugger’ statement. This is handy in two cases:

A) When the JavaScript file is hard to navigate into (this is true for complex web apps with lots of scripts, iframes, etc).

// cause the debugger to fire every time
debugger;

B) The breakpoint should only fire for a certain condition.

// example 2, only if the force is with us, do we get a breakpoint
if(theForceIsWithUs) {
    debugger;
}

Yoda Quote: “Though powerful the debugger statement is, there is a darkness surrounding it.  End with nerd ridicule and screaming customers debugger statements that go into production do, yes.. Eh hi hi hi hee…

 

3)  Webstorm by IDEA supports setting breakpoints in the IDE. This requires launching the JavaScript debugger from IDEA. It must be configured in advance so it understands how to map JavaScript on the development server to JavaScript files in your environment. IDEA will automatically install a Chrome or Firefox plug-in to facilitate. This is pretty new technology and can be touchy.

Webstorm set breakpoint

Closing Thoughts:

Forget all those console.log(x) statements or alert(z) dialogs *shudder*.

Breakpoints are a powerful tool the pros in established languages like C++ and Java swear by. There is a misconception out there that JavaScript cannot do breakpoints, unit tests, code analysis, etc. That was absolutely true in the days of Netscape 2.0. However, times have changed.

Back in 1995, who would have thought JavaScript would be the language of choice for the future? With the best minds in the world working on things like the Google V8 engine and Node.js JavaScript will only get more momentum (and better tools).

 

Enjoy!

This entry was posted in Application Development and tagged , . Bookmark the permalink.

Comments are closed.