Debug JavaScript in the Browser: Breakpoints, Console, Network
You do not need to install anything to debug JavaScript well. Every current browser ships developer tools (DevTools) with a debugger, a console and a network inspector, and they solve most bugs faster than adding console.log lines and reloading. This page walks through a repeatable workflow using a real bug. Examples are plain JavaScript that runs in a current browser or Node.js 22 or later. Panel names below are Chrome's (Edge is the same); Firefox and Safari have equivalent panels with slightly different names.
Open DevTools and know the three panels you need
Press F12, or Ctrl+Shift+I on Windows and Linux, Cmd+Option+I on macOS. In Safari, first turn on the developer features in Safari's settings (Advanced tab). Three panels do most of the work:
- Console: errors, warnings and your own log output, plus a prompt where you can evaluate expressions in the page.
- Sources (Firefox: Debugger): your code, breakpoints, the call stack and the current values of variables.
- Network: every request the page makes, with its status code, headers, timing and response body.
Step 1: read the error before you change anything
Open the Console and reload. An uncaught error shows its type, its message and a link such as app.js:14 to the line that threw. Click the link to jump to that line in Sources. Expand the error to see the stack trace: the list of function calls that led there, newest first. The bug is often one or two frames down, in the code that passed a bad value, not on the line that threw.
The error types tell you what kind of problem you have:
| Error | Usually means |
|---|---|
TypeError: Cannot read properties of undefined (reading 'x') | Something you expected to be an object is undefined: a missing field in data, a wrong index, or code running before the data arrived. |
ReferenceError: x is not defined | A misspelled name, a variable used outside its scope, or a script that did not load. |
SyntaxError | The file could not be parsed at all, or JSON.parse was given text that is not valid JSON (often an HTML error page). |
Uncaught (in promise) | A rejected promise nobody handled with await inside try/catch or with .catch(). |
Step 2: reproduce the bug with the smallest input
Here is a bug with no error message at all, which is the harder kind. A shopping cart adds up prices read from form fields:
// Values read from <input> elements are always strings.
const prices = ["2.50", "1.25"];
function cartTotal(prices) {
let total = 0;
for (const p of prices) {
total += p;
}
return total;
}
console.log(cartTotal(prices));
It prints 02.501.25 instead of 3.75. Nothing threw, so the Console alone will not help. This is where the debugger earns its place.
Step 3: pause the code with a breakpoint
In Sources, open the file and click the line number of total += p;. A marker appears. Trigger the code again and execution stops before that line runs. While paused you can:
- Hover over any variable to see its current value, or read them all in the Scope section.
- Type expressions in the Console, such as
typeof p, and they run in the paused function's scope. Here it answers'string', which is the bug:+with a string concatenates instead of adding. - Step with the toolbar or keyboard: F8 resume, F10 step over the next line, F11 step into a function call, Shift+F11 step out of the current function.
- Add expressions to Watch so you can see them change at every step.
Other breakpoint types save a lot of clicking:
- Conditional breakpoint: right-click the line number, choose "Add conditional breakpoint" and type a condition such as
typeof p !== "number". It pauses only when the condition is true, which matters inside a loop that runs a thousand times. - Logpoint: right-click, "Add logpoint", and enter a message such as
'p is', p. It logs to the Console without pausing and without editing your code, so there is no strayconsole.logto forget in a commit. - Exception breakpoints: in the Breakpoints section, tick "Pause on uncaught exceptions" (and "Pause on caught exceptions" if a
try/catchis hiding the error). The debugger stops at the exact line that throws, with all variables still in scope. - DOM, event listener and XHR/fetch breakpoints: pause when an element changes, when a
clickhandler runs, or when a request to a URL containing some text is sent. Useful when you do not know which code is responsible. - The
debugger;statement in your source pauses there whenever DevTools is open. Remove it before committing; a linter rule can enforce that.
Step 4: fix the cause and check it
The fix converts each value to a number and rejects anything that is not one, instead of letting a bad value flow on silently:
const prices = ["2.50", "1.25"];
function cartTotal(prices) {
let total = 0;
for (const p of prices) {
const n = Number(p);
if (!Number.isFinite(n) || n < 0) {
throw new RangeError(`Invalid price: ${JSON.stringify(p)}`);
}
total += n;
}
return total;
}
console.table(prices.map((p) => ({ raw: p, type: typeof p, asNumber: Number(p) })));
console.log(cartTotal(prices));
Output in Node.js (the browser Console shows the same table as a grid):
┌─────────┬────────┬──────────┬──────────┐
│ (index) │ raw │ type │ asNumber │
├─────────┼────────┼──────────┼──────────┤
│ 0 │ '2.50' │ 'string' │ 2.5 │
│ 1 │ '1.25' │ 'string' │ 1.25 │
└─────────┴────────┴──────────┴──────────┘
3.75
The check that it worked is the original reproduction giving the right answer, plus one input that should fail (an empty field or "abc") failing loudly. For real money, store amounts as integer cents to avoid floating-point rounding; this example keeps decimals only to stay short.
Use the Console for more than console.log
console.table(arrayOfObjects)shows rows and columns, as above, which makes a wrong field in one record easy to spot.console.errorandconsole.warnare styled and filterable by level, so you can hide the noise.console.trace()prints the call stack at that point: the fastest answer to "who is calling this?".console.group()andconsole.groupEnd()nest related output;console.time(label)andconsole.timeEnd(label)measure how long something took.console.assert(condition, message)logs only when the condition is false.
One trap: logging an object in the browser shows a live reference. If you expand it later, you see its current contents, not what it held when the line ran. Log structuredClone(obj) or JSON.stringify(obj) when the timing matters, or use a breakpoint instead.
Use the Network panel for anything involving a server
Many "JavaScript bugs" are really a request that failed. Open Network, reload, and click the request to see its status, request headers, payload and response. Two checkboxes help: Preserve log keeps requests across page navigations and redirects, and Disable cache makes sure you are testing the latest files (it applies only while DevTools is open). Filter by Fetch/XHR to hide images and stylesheets.
What to look for:
- Red rows: 4xx (your request was wrong or unauthorized) or 5xx (the server failed). The Response tab often explains why.
- A JSON endpoint that returned HTML: the response starts with
<!DOCTYPE html>and your code throwsSyntaxError: Unexpected token '<'. The URL is wrong or a login page or error page came back. To read a large JSON response, paste it into the JSON Formatter. - CORS errors in the Console: the browser blocked reading the response because the server did not allow your origin. The fix is on the server (its
Access-Control-Allow-Originresponse), not in your fetch code.
A common cause of silent failures is assuming fetch() rejects on an error status. It does not: per the MDN documentation for Response.ok, a 404 or 500 still resolves, so check res.ok yourself:
async function loadUser(id) {
const res = await fetch(`/api/users/${encodeURIComponent(id)}`);
if (!res.ok) {
// fetch() only rejects on network failure; a 404 or 500 still resolves.
throw new Error(`HTTP ${res.status} ${res.statusText} for ${res.url}`);
}
return res.json(); // throws a SyntaxError if the body is not valid JSON
}
Tested against a local server, a valid id returns the parsed object, and a missing one throws HTTP 404 Not Found for http://127.0.0.1:59440/api/users/a%2Fb (the port varies). encodeURIComponent keeps a value such as a/b from changing the path.
Debugging Node.js with the same tools
Run node --inspect-brk app.js. Node.js starts an inspector and pauses before your first line. Open chrome://inspect in Chrome (or edge://inspect in Edge), find your script under Remote Target and click inspect, and you get the same Sources panel with breakpoints and stepping. Use --inspect instead if you do not want the initial pause. The inspector listens on 127.0.0.1:9229 by default; keep it bound to localhost, because anyone who can reach that port can run code in your process. See the Node.js debugging guide for details.
Common mistakes
- Changing code before reading the stack trace. The first clue is usually in the message you skipped.
- Debugging minified code. Make sure your build produces source maps for development so Sources shows your original files and line numbers.
- Testing a stale file. Use Disable cache, or a hard reload, before deciding a fix "did not work".
- Swallowing errors. An empty
catch {}hides the bug you are hunting. Log or rethrow. - Leaving debug code behind. Prefer logpoints to
console.log, and let a linter flag leftoverdebuggerstatements.
Many of these bugs can be caught before the code ever runs: see linters and static analysis. For a list of the mistakes that cause them, read 10 common JavaScript mistakes and how to fix them.