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:
- 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. - First open the chrome developer tools by right clicking anywhere on the page and then clicking on inspect element as shown below:
- Make sure source tab is selected in the chrome developer tools. Then select the source file containing the javascript code as shown below:
- Locate the desired javascript code in the source file and click on the line number to add a breakpoint as shown below:
- 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:
- 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.