JS Debugging
Every browser ships powerful dev tools: a console, a step debugger, network inspector, and a performance profiler. Knowing the basics turns "stare at the code" into "watch the code run."
The five techniques
| Technique | How |
|---|---|
| console.log | Sprinkle messages. Quick and disposable. |
| debugger statement | Type debugger; in source. DevTools pause there. |
| Breakpoints | Click the gutter in DevTools' Sources panel. Conditional breakpoints take an expression. |
| Watch expressions | Add an expression to the Watch panel — it re-evaluates as you step. |
| Network & Performance tabs | For "why is it slow?" instead of "why is it wrong?". |
The console is more than log
JS
console.log("plain");
console.info("informational");
console.warn("yellow triangle");
console.error("red box + stack trace");
console.table([{ name: "Ada" }, { name: "Grace" }]);
console.group("user fetch");
console.log("status", 200);
console.log("body", body);
console.groupEnd();
console.time("query");
const rows = await db.query("…");
console.timeEnd("query"); // "query: 14.2 ms"
console.assert(rows.length > 0, "expected rows");
console.trace(); // current stack trace
Stepping in the debugger
| Key | Action |
|---|---|
| F8 / Resume | Run to the next breakpoint. |
| F10 / Step over | Run the current line, stop on the next. |
| F11 / Step into | Enter the called function. |
| Shift+F11 / Step out | Run the rest of the function and stop after the return. |
Tip: Right-click in the Sources panel for "Add conditional breakpoint" or "Add logpoint". Logpoints log expressions without modifying source — perfect for production debugging via source maps.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Debugging!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Add a line that drops you into the debugger when DevTools is open.
function buggy() {
; doWork(); }
Eight letters.
Discussion
Loading…