Debugging JavaScript

  1. Debugging JavaScript can be difficult if you don't know where to look when errors occur
    1. The browser will normally not display anything to the user indicating something is wrong
    2. Most browsers have a mechanism to view JavaScript errors (in Chrome, use Ctrl-Shift-J to see the JavaScript Console)
    3. Deciphering the reported errors takes some getting used to
    4. JSLint can be helpful at catching some bugs
  2. Logging output
    1. All browsers contain a log which developers can use to view debugging statements from their code
    2. Output to the log using console.log(message)
      var x = 10;
      console.log("x is " + x);
      
    3. See log output in Chrome's JavaScript Console (Ctrl-Shift-J)

      Console output in the JavaScript Console
    4. Other methods include console.error(), console.warn() and others
    5. Learn more: Tips and Tricks for using Chrome's console
    6. Use the alert function to pause execution
  3. Most browsers have a built-in JavaScript debugger that works like Visual Studio's debugger
    1. Open the Chrome developer tools by pressing Ctrl+Shift+I
    2. Select Sources tab, and select the file that contains the JavaScript you want to debug on the left
    3. Set a breakpoint by clicking on an executable line number (a breakpoint was placed on line 26 below

      Chrome debugger
    4. When the line of JavaScript containing the breakpoint is about to be executed, the browser will pause. You can step through the code using the buttons circled (F10 to step over, F11 to step into, F8 to continue execution) and examine variables by putting the mouse cursor on them or observing their values on the pane on the right

      Chrome debugger