Browser DevTools are the workshop where you find out why a page is not doing what you think it should do. The Console panel answers the quick questions, and the Sources panel catches the ones that only appear while the code is running. A handful of console commands make both of them dramatically faster. Here is a workflow that you can use on every bug from your first week onward.
The previous lesson in this module covered "Your First Script and console.log", and the next lesson in this module is about "Comments and Basic Code Hygiene".
Which DevTools panel answers which question?
DevTools is a large interface, and beginners tend to move between panels without a plan. Each panel answers a different kind of question.
| Panel | The question it answers |
|---|---|
| Console | What does this code produce, and what error did it throw? |
| Sources | Which line is running, and what are my variables right now? |
| Elements | What does the DOM look like right now, and did my script change it? |
| Network | What requests did the page make, and what came back? |
| Application | What is stored in localStorage, in cookies, and in the cache? |
| Performance | Where did the time go? |
Most of the time you need two of them at once, with the Console at the bottom and the Sources panel in the main area, docked side by side. Press F12 on Windows and Linux, or Cmd + Option + I on macOS. If nothing happens, the browser probably opened it in a separate window, so drag the panel back to the bottom or use the three-dot menu in the top right of DevTools to change how it is docked.
What can the console do besides print?
It is an evaluation environment. Anything that you type is worked out as JavaScript and the result is shown to you, which makes it the fastest way to poke at a live page.
// Grouped output keeps a noisy console readable.
console.group("Cart");
console.log("items:", 3);
console.log("total:", 249.5);
console.groupEnd();
// A running counter, which is handy inside a loop.
for (const step of ["add", "remove", "clear"]) {
console.count(step);
}
// Timing a block without leaving the page.
console.time("parse");
const payload = JSON.parse('{"items": 3}');
console.timeEnd("parse");
console.log(payload.items);
The console.count calls print the label followed by a running total, so you can see how many times each label fired. The console.time and console.timeEnd pair prints the elapsed milliseconds for that label when it ends. Neither of those exists in the browser console panel by default, because they are Node.js additions, so the snippet above runs under node and not in the browser console.
Two more console-only helpers are worth stealing. copy(anything) puts the value on your clipboard, and table(rows) renders an array of records as an aligned table that is much easier to compare than a long vertical list.
const rows = [
{ city: "Pune", rainfall: 82 },
{ city: "Delhi", rainfall: 24 },
{ city: "Kochi", rainfall: 118 },
];
console.table(rows);
Three cities, three rainfall figures, and one aligned table. When you are comparing records, that is the difference between scanning the output and actually reading it.
How do breakpoints actually work?
A breakpoint is an instruction to the engine to pause before it runs a particular line. Open the Sources panel, find your file in the file tree, and click the line number to set one. When the code reaches that line, the execution stops, and you can inspect the live state of every variable that is in scope.
Three controls matter while the code is paused. Step over runs the current line and stops at the next one inside the same function, ignoring any function calls. Step into descends into a function that was called. Step out finishes the current function and returns to the caller. The Watch panel on the right lets you pin expressions, so that their values update on every step. That is how you watch a variable change without adding console noise.
You can also set a breakpoint that only fires under a condition. Right-click the line number and choose Add conditional breakpoint, and then type a condition such as user.id === 42. The debugger now pauses only for that user, and it skips the breakpoint on every other run. For the same effect without stopping, use a logpoint. It prints a message to the console every time the line runs and it never pauses, which is often better than a breakpoint because the program keeps its pace.
What is the debugger statement for?
There is a keyword that you can drop into any line of code to make the DevTools open at that exact point. It is useful when you do not want to hunt for the line in a large file.
function calculateShipping(weightKg, zone) {
debugger;
const basePaise = 450;
const perKgPaise = zone === "remote" ? 225 : 110;
return basePaise + weightKg * perKgPaise;
}
console.log("standard:", calculateShipping(12, "city"));
console.log("remote:", calculateShipping(12, "remote"));
Run that with node and nothing appears to happen, because the statement does nothing unless a debugger is attached. Open the file in the browser Sources panel with DevTools open, and the browser pauses on that line with every variable in scope visible. The two lines after it then run one at a time as you step through them.
There are two cautions. The debugger statement ships to production if you forget it, and it will freeze the page for any user whose DevTools are open. Treat it like a console.log and remove it before you commit.
How do you inspect a live value precisely?
The browser console has a handful of variables that refer to what you currently have selected in the Elements panel. $0 is the selected element, $1 is the one that was selected before it, and $_ is the last expression that you evaluated. $$("selector") returns every element that matches a CSS selector as an array, and copy() drops a value into your clipboard.
// Inspect the first matching element on the page.
const heading = document.querySelector("h1");
console.dir(heading);
console.log("text:", heading.textContent);
That snippet needs a page to run against, which is why it lives in the browser console and not in a Node script. In the Elements panel, click an element, then type $0.className in the console, and you get that element's classes without touching your source at all. To capture a value rather than read it, type copy($0.outerHTML). copy() is a DevTools helper and not a language feature, so it only exists inside the console.
One subtlety is worth knowing. When the browser console displays an object, it works out the getters at the moment you expand it. If an object has a getter that throws, expanding it in the console can produce an error that never happens during normal use. console.dir on a plain data object behaves in the same way, which is another reason to prefer logging plain values while you are hunting for a bug.
What workflow should you follow when something breaks?
Reproduce first, always. Open DevTools, reproduce the problem, and note the exact error message together with the first line of the stack trace. That stack trace is the most useful thing on the screen, and it is the part that people skip.
Then narrow the scope. The error message tells you the type. A TypeError usually means that a value was not what you assumed. A ReferenceError means that a name does not exist in that scope. A SyntaxError means that the file did not even parse. That distinction tells you whether to set a breakpoint for a runtime problem, or to reread the file for a syntax problem.
Then inspect instead of guessing. Set a breakpoint just before the wrong value is produced, open the Watch panel, and look at the data. Guessing at the cause produces code that logs more and fixes nothing.
Then fix it and check it again in the same session. A fix that you have not re-run is only a hypothesis.
The short version
- Use the Console for questions, Sources for state, Elements for the DOM, Network for requests, and Application for storage.
- The console works out expressions.
$0,$$, andcopy()save you from opening files. - Step over, step into, and step out are the three controls that you will use most while the code is paused.
- Conditional breakpoints and logpoints beat unconditional ones, because they narrow the noise instead of adding to it.
- Reproduce, read the stack trace, narrow the type of the error, inspect the live values, fix, and then run it again.
Try it yourself: Take the counter page from the previous lesson and break it on purpose. Remove the defer attribute so that the script runs before the button exists. Open DevTools, reload the page, and read the error and the stack trace. Then set a conditional breakpoint on the click handler, click the button five times, and watch the counter variable update in the Watch panel on every step. Fix the ordering, reload, and confirm that the error is gone. Reading the failure is faster than guessing at it.