how to debug javascript in Chrome

Chrome developer tools can be used to debug javascript by inserting break point in the javascript code. This is pretty handy to not only debug javascript, but can also be used to understand existing javascript code on a site. Here are steps to debug javascript using chrome developer tools:

  1. We will be using the following code to debug javascript in Chrome:
    <!doctype html>
    <html>
    <head>
    <title>Chrome developer tools - debug javascript example</title>
    </head>
    <body>
    <h1>Chrome developer tools - debug javascript example</h1>
    <script type="text/javascript">
    function foo() {
      var a = 10;
      var b = 20;
      var c = a + b;
      var elem = document.getElementById("res");
      var existingVal = parseInt(elem.textContent);
      elem.textContent = existingVal + c;
    }
    </script>
    <a href="" onclick="foo(); return false;">clickme</a> (to add 30 to the number below)
    <div id="res">0</div>
    </body>
    </html>
    
    You can see the live demo at chrome developers tools – debug javascript example.
  2. First open the chrome developer tools by right clicking anywhere on the page and then clicking on inspect element as shown below:
    chrome-right-click-inspect-element
  3. Make sure source tab is selected in the chrome developer tools. Then select the source file containing the javascript code as shown below:
    chrome-developer-tools-source-file
  4. Locate the desired javascript code in the source file and click on the line number to add a breakpoint as shown below:
    chrome-developer-tools-js-code-break-point
  5. Now click on the link clickme in demo page which triggers the code. Here is how the ui looks when the debugger is at a specific break point:
    chrome-developer-tools-in-debug
  6. You can click on “step over next function call” icon to run code to next line. In case you want to resume the script, then you can use “resume script execution” icon.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments