Debug JavaScript

Kayce Basques
Kayce Basques
Sofia Emelianova
Sofia Emelianova

This tutorial teaches you the basic workflow for debugging any JavaScript issue in DevTools. Readon, or watch the video version of this tutorial.

Reproduce the bug

Finding a series of actions that consistently reproduces a bug is always the first step todebugging.

  1. Open this demo in a new tab.
  2. Enter5 in theNumber 1 box.
  3. Enter1 in theNumber 2 box.
  4. ClickAdd Number 1 and Number 2. The label below the button says5 + 1 = 51. The resultshould be6. This is the bug you're going to fix.

The result of 5 + 1 is 51. It should be 6.

In this example, the result of 5 + 1 is 51. It should be 6.

Get familiar with the Sources panel UI

DevTools provides a lot of different tools for different tasks, such as changing CSS, profiling pageload performance, and monitoring network requests. TheSources panel is where you debugJavaScript.

  1. Open DevTools and navigate to theSources panel.

    The Sources panel.

TheSources panel has three sections:

The 3 sections of the Sources panel.

  1. ThePage tab with the file tree. Every file that the page requests is listed here.
  2. TheCode Editor section. After selecting a file in thePage tab, the contents ofthat file are displayed here.
  3. TheDebugger section. Various tools for inspecting the page's JavaScript.

    If your DevTools window is wide, by default, theDebugger is to the right of theCode Editor. In this case, theScope andWatch tabs joinBreakpoints,Call stack, and others as collapsible sections.

The Debugger to the right of the wide window.

Pause the code with a breakpoint

A common method for debugging a problem like this is to insert a lot ofconsole.log() statementsinto the code, in order to inspect values as the script executes. For example:

functionupdateLabel(){varaddend1=getNumber1();console.log('addend1:',addend1);varaddend2=getNumber2();console.log('addend2:',addend2);varsum=addend1+addend2;console.log('sum:',sum);label.textContent=addend1+' + '+addend2+' = '+sum;}

Theconsole.log() method may get the job done, butbreakpoints can get it done faster. Abreakpoint lets you pause your code in the middle of its execution, and examine all values at thatmoment in time. Breakpoints have a few advantages over theconsole.log() method:

  • Withconsole.log(), you need to manually open the source code, find the relevant code, inserttheconsole.log() statements, and then reload the page in order to see the messages in theConsole. With breakpoints, you can pause on the relevant code without even knowing how the code isstructured.
  • In yourconsole.log() statements you need to explicitly specify each value that you want toinspect. With breakpoints, DevTools shows you the values of all variables at that moment in time.Sometimes there are variables affecting your code that you're not even aware of.

In short, breakpoints can help you find and fix bugs faster than theconsole.log() method.

If you take a step back and think about how the app works, you can make an educated guess that theincorrect sum (5 + 1 = 51) gets computed in theclick event listener that's associated to theAdd Number 1 and Number 2 button. Therefore, you probably want to pause the code around the timethat theclick listener executes.Event Listener Breakpoints let you do exactly that:

  1. In theDebugger section, clickEvent Listener Breakpoints to expand thesection. DevTools reveals a list of expandable event categories, such asAnimation andClipboard.
  2. Next to theMouse event category, clickExpand.DevTools reveals a list of mouse events, such asclick andmousedown. Each event has a checkbox next to it.
  3. Check theclick checkbox. DevTools is now set up to automatically pause whenanyclickevent listener executes.

    The 'click' checkbox is enabled.

  4. Back on the demo, clickAdd Number 1 and Number 2 again. DevTools pauses the demo andhighlights a line of code in theSources panel. DevTools should be paused on this line ofcode:

    functiononClick(){

    If you're paused on a different line of code, pressResume Script Execution until you're paused on the correct line.

    Note: If you paused on a different line, you have a browser extension that registers aclick event listener on every page that you visit. You were paused in the extension'sclicklistener. If you use Incognito Mode tobrowse in private, which disables all extensions,you can see that you pause on the correct line of code every time.

Event Listener Breakpoints are just one of many types of breakpoints available in DevTools. It'sworth exploring all the different types, because each type ultimately helps you debug differentscenarios as quickly as possible. SeePause Your Code With Breakpoints to learn when and how touse each type.

Step through the code

One common cause of bugs is when a script executes in the wrong order. Stepping through your codelets you walk through your code's execution, one line at a time, and figure out exactly whereit's executing in a different order than you expected. Try it now:

  1. On theSources panel of DevTools, clickStep into next function call to step through the execution of theonClick() function, one line at a time. DevTools highlights the following line of code:

    if(inputsAreEmpty()){
  2. ClickStep over next function call.

    DevTools executesinputsAreEmpty() without stepping into it. Notice how DevTools skips a few lines ofcode. This is becauseinputsAreEmpty() evaluated to false, so theif statement's block ofcode didn't execute.

That's the basic idea of stepping through code. If you look at the code inget-started.js, you cansee that the bug is probably somewhere in theupdateLabel() function. Rather than stepping throughevery line of code, you can use another type of breakpoint to pause the code closer to the probablelocation of the bug.

Set a line-of-code breakpoint

Line-of-code breakpoints are the most common type of breakpoint. When you've got a specific line ofcode that you want to pause on, use a line-of-code breakpoint:

  1. Look at the last line of code inupdateLabel():

    label.textContent=addend1+' + '+addend2+' = '+sum;
  2. To the left of the code you can see the line number of this particular line of code, which is32. Click32. DevTools puts a blue icon on top of32. This means that there is aline-of-code breakpoint on this line. DevTools now always pauses before this line of code isexecuted.

  3. ClickResume script execution. Thescript continues executing until it reaches line 32. On lines 29, 30, and 31, DevToolsshows the values ofaddend1,addend2, andsum inline next to their declarations.

DevTools pauses on the line-of-code breakpoint on line 32.

In this example, DevTools pauses on the line-of-code breakpoint on line 32.

Check variable values

The values ofaddend1,addend2, andsum look suspicious. They're wrapped in quotes, whichmeans that they're strings. This is a good hypothesis for the explaining the cause of the bug. Nowit's time to gather more information. DevTools provides a lot of tools for examining variablevalues.

Method 1: Inspect the Scope

When you're paused on a line of code, theScope tab shows you what local and global variablesare defined at this point in execution, along with the value of each variable. It also shows closure variables, whenapplicable. When you're not paused on a line of code, theScope tab is empty.

Double-click a variable value to edit it.

Note: Depending on yourlayout preference and the width of your DevTools window, theScope tab may appear as a collapsible section together withBreakpoints andCall stack.

The Scope pane.

Method 2: Watch expressions

TheWatch tab lets you monitor the values of variables over time.Watch isn't just limited to variables. You can store any valid JavaScriptexpression in theWatch tab.

Note: Depending on yourlayout preference and the width of your DevTools window, theWatch tab may appear as a collapsible section together withBreakpoints andCall stack.

Try it now:

  1. Click theWatch tab.
  2. ClickAdd watch expression.
  3. Typetypeof sum.
  4. PressEnter. DevTools showstypeof sum: "string". The value to the right of the colon is theresult of your expression.

The Watch Expression pane

This screenshot shows theWatch tab (bottom-right) after creating thetypeof sum watchexpression.

As suspected,sum is being evaluated as a string, when it should be a number. You've now confirmedthat this is the cause of the bug.

Method 3: The Console

In addition to viewingconsole.log() messages, you can also use the Console to evaluate arbitraryJavaScript statements. In terms of debugging, you can use the Console to test out potential fixesfor bugs. Try it now:

  1. If you don't have the Console drawer open, pressEscape to open it. It opens at the bottom ofyour DevTools window.
  2. In the Console, typeparseInt(addend1) + parseInt(addend2). This statement works because youare paused on a line of code whereaddend1 andaddend2 are in scope.
  3. PressEnter. DevTools evaluates the statement and prints out6, which is the result you expectthe demo to produce.

The Console drawer, after evaluating variables that are in scope.

This screenshot shows theConsole drawer after evaluatingparseInt(addend1) + parseInt(addend2).

Apply a fix

You've found a fix for the bug. All that's left is to try out your fix by editing the code andre-running the demo. You don't need to leave DevTools to apply the fix. You can edit JavaScript codedirectly within the DevTools UI. Try it now:

  1. ClickResume script execution.
  2. In theCode Editor, replace line 31,var sum = addend1 + addend2, withvar sum = parseInt(addend1) + parseInt(addend2).
  3. PressCommand +S (Mac) orControl +S (Windows, Linux) to save your change.
  4. ClickDeactivate breakpoints.Its color changes to blue to indicate that it's active. While this is set, DevTools ignores anybreakpoints you've set.
  5. Try out the demo with different values. The demo now calculates correctly.
Caution: This workflow only applies a fix to the code that is running in your browser. It won'tfix the code for all users that visit your page. To do that, you need to fix the code that's on yourservers. You can, however,edit files in DevTools and save them to your sources with Workspaces.Tip: Starting from Chrome version 105, you canEdit a paused function live.

Next steps

Success: Congratulations! You now know how to make the most of Chrome DevTools when debugging JavaScript. Thetools and methods you learned in this tutorial can save you countless hours.

This tutorial only showed you two ways to set breakpoints. DevTools offers many other ways,including:

  • Conditional breakpoints that are only triggered when the condition that you provide is true.
  • Breakpoints on caught or uncaught exceptions.
  • XHR breakpoints that are triggered when the requested URL matches a substring that you provide.

SeePause Your Code With Breakpoints to learn when and how to use each type.

There's a couple of code stepping controls that weren't explained in this tutorial. SeeStep overline of code to learn more.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-05-22 UTC.