This tutorial teaches you the essential workflow for debugging any JavaScript issue in DevTools. Dive in to learn how to efficiently identify and fix bugs using this powerful tool.

Reproduce the Bug

To start debugging, it's crucial to reproduce the bug consistently. In this example, we'll explore a scenario where the sum of two numbers is incorrect.

Open the demo in a new tab and enter 5 in the Number 1 box and 1 in the Number 2 box. Click Add Number 1 and Number 2. The label below the button displays an incorrect result: 51 instead of 6. This is the bug we're going to fix.

Get Familiar with the Sources Panel UI

DevTools provides a range of tools for various tasks, including modifying CSS, profiling page load performance, and monitoring network requests. The Sources panel is where you debug JavaScript.

Open DevTools and navigate to the Sources panel. You'll see three sections: the Page tab, the Code Editor section, and the Debugger section. Each section serves a specific purpose in the debugging process.

Pause the Code with Breakpoints

One efficient method for debugging is to insert breakpoints into your code. This allows you to pause the code at a specific point and examine all variables at that moment.

Let's set a breakpoint in our example. In the Debugger section, click Event Listener Breakpoints to expand the section. Next, find the Mouse event category and check the click checkbox. DevTools is now set up to automatically pause when any click event listener executes.

Back on the demo, click Add Number 1 and Number 2 again. DevTools pauses the demo and highlights a line of code in the Sources panel. You can now step through the code or inspect variables at this moment.

Step Through the Code

Stepping through your code lets you walk through its execution, one line at a time, to figure out where it's executing in a different order than expected.

In our example, let's step through the execution of the onClick() function. On the Sources panel, click Step into next function call to start stepping through the code. DevTools highlights each line as you execute it.

Set a Line-of-Code Breakpoint

Line-of-code breakpoints are the most common type of breakpoint. When you know a specific line of code that you want to pause on, use this type of breakpoint.

Look at the last line of code in updateLabel(): label.textContent = addend1 + ' + ' + addend2 + ' = ' + sum; To set a line-of-code breakpoint, click the line number (32) to the left of the code. DevTools puts a blue icon on top of 32, indicating that there is a line-of-code breakpoint on this line.

Now, when you run the script, it will always pause before executing this line of code. You can inspect variables or step through the code from here.