Debugging JavaScript in VS Code, Node.js and Chrome DevTools
Debugging is the skill that separates a tester who reports “the test is failing” from one who reports “the test fails because the API returns the price as a string since build 4512”. In this lesson you will learn a repeatable debugging process, how to read stack traces (including async ones), how to use breakpoints, conditional breakpoints, logpoints and watches in VS Code, how to debug Node.js with Chrome DevTools, how to debug code running in the browser, and the tools Playwright gives you for debugging tests.
📖 What You’ll Learn: a step-by-step debugging process, reading synchronous and async stack traces, targeted logging and util.inspect, debug logging switched on by environment variables, VS Code breakpoints, conditional breakpoints, logpoints, exception breakpoints, watches and the call stack, launch.json, node –inspect with Chrome DevTools, debugging browser code in the Sources panel, source maps, Playwright debugging tools, and a checklist of common bugs.
🧭 A Debugging Process That Works
Definition: debugging is finding the cause of a difference between what the code should do and what it actually does, then fixing it. Guessing and changing code randomly wastes hours; a process finds the cause quickly:
- Reproduce the problem reliably. Note the exact input, environment and steps. A bug you cannot reproduce cannot be confirmed as fixed.
- Read the error fully: type, message and the first stack frame in your own code.
- Isolate it: shrink the input or the code until the problem disappears; the last change points at the cause.
- Form a hypothesis (“the price is a string, not a number”) and check it with a breakpoint or a log, not by assuming.
- Fix the cause, not the symptom, and add a test or assertion so it cannot come back unnoticed.
💡 Tip: Explaining the code line by line to someone else, or even to a rubber duck on your desk, often reveals the bug. Saying “and here the value is definitely a number” out loud makes you notice that you never checked.
📜 Reading Stack Traces
A stack trace lists the function calls that were active when the error happened, most recent first. Find the first line that points into your code; that is usually where to start.
📄 stack.js
function parsePrice(text) {
return text.replace("₹", ""); // fails if text is not a string
}
function lineTotal(item) {
return Number(parsePrice(item.price)) * item.qty;
}
function cartTotal(items) {
return items.reduce((sum, item) => sum + lineTotal(item), 0);
}
console.log(cartTotal([{ price: "₹10", qty: 2 }, { price: 45, qty: 1 }]));
⌨️ Terminal
node stack.js
🖥️ Output
/home/you/js-course/stack.js:2
return text.replace("₹", ""); // fails if text is not a string
^
TypeError: text.replace is not a function
at parsePrice (/home/you/js-course/stack.js:2:15)
at lineTotal (/home/you/js-course/stack.js:5:17)
at /home/you/js-course/stack.js:8:44
at Array.reduce (<anonymous>)
at cartTotal (/home/you/js-course/stack.js:8:16)
at Object.<anonymous> (/home/you/js-course/stack.js:11:13)
Node.js v26.13.0
- Line 1 of the trace shows the source line and a caret
^at the failing expression. TypeError: text.replace is not a function:textwas not a string (it was the number 45).- Read down the frames:
parsePrice←lineTotal← thereducecallback ←cartTotal. The data came from the second cart item.
Async stack traces
With async/await, Node.js keeps the chain of awaiting functions in the trace, shown as at async ...:
📄 async-stack.js
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
async function fetchUser(id) {
await delay(5);
if (id === 0) throw new Error(`User ${id} not found`);
return { id };
}
async function loginAs(id) {
const user = await fetchUser(id);
return user;
}
async function runTest() {
await loginAs(0);
}
runTest().catch((e) => console.log(e.stack));
⌨️ Terminal
node async-stack.js
🖥️ Output
Error: User 0 not found
at fetchUser (/home/you/js-course/async-stack.js:5:23)
at async loginAs (/home/you/js-course/async-stack.js:9:16)
at async runTest (/home/you/js-course/async-stack.js:13:3)
⚠️ Watch out: The async chain is only kept when every step is awaited. If a function returns a promise without awaiting it, or uses .then callbacks, frames can disappear from the trace, which makes failures much harder to locate.
🔎 Targeted Logging
Logging is still the fastest tool for many problems, when it is targeted: log the exact values your hypothesis depends on, with labels, at the point where you suspect things go wrong.
📄 targeted-log.js
const util = require("node:util");
const response = { status: 200, body: { data: { items: [{ id: 1, price: "499" }, { id: 2, price: null }] } } };
console.log("price types:", response.body.data.items.map((i) => `${i.id}:${typeof i.price}`));
console.log(util.inspect(response, { depth: null, colors: false, compact: 3 }));
console.log({ status: response.status, count: response.body.data.items.length }); // label values with an object
⌨️ Terminal
node targeted-log.js
🖥️ Output
price types: [ '1:string', '2:object' ]
{
status: 200,
body: {
data: { items: [ { id: 1, price: '499' }, { id: 2, price: null } ] }
}
}
{ status: 200, count: 2 }
- Log types as well as values:
"499"and499look the same in many outputs. util.inspect(value, { depth: null })prints nested objects completely (see the Console Methods lesson).- Wrapping values in an object,
console.log({ status, count }), prints their names too.
Debug logging you can switch on
Instead of adding and deleting logs, keep useful debug output behind a switch. Node.js has a built-in helper, util.debuglog, that prints only when the section name is listed in the NODE_DEBUG environment variable:
📄 orders.js
const util = require("node:util");
const log = util.debuglog("orders");
log("loaded %d orders", 3); // printed only with NODE_DEBUG=orders
console.log("done");
⌨️ Terminal
node orders.js
NODE_DEBUG=orders node orders.js
🖥️ Output (run twice; 12345 is the process ID and changes every run)
done
ORDERS 12345: loaded 3 orders
done
On Windows PowerShell set the variable first: $env:NODE_DEBUG="orders"; node orders.js. Libraries such as debug use the same idea with a DEBUG variable, and Playwright prints its internal logs with DEBUG=pw:api.
🐞 Breakpoints in VS Code
A breakpoint pauses the program at a line so you can inspect every variable, step through the code, and evaluate expressions, without editing the code.
- Open the file and click in the gutter left of a line number to add a red breakpoint dot.
- Open Run and Debug (Ctrl+Shift+D) and click Run and Debug, or press F5 and choose Node.js.
- When execution pauses, use the panels: Variables (all values in scope), Watch (expressions you add), Call Stack (who called this), and the Debug Console (run any expression in the paused context).
- Step with Continue (F5), Step Over (F10), Step Into (F11) and Step Out (Shift+F11).
| Breakpoint type | How to add (right-click the gutter) | Use it when |
|---|---|---|
| Conditional breakpoint | “Add Conditional Breakpoint”, for example item.price === null | A bug only happens for one item in a loop of hundreds |
| Hit count | Conditional breakpoint → Hit Count, for example 50 | Pause on the 50th iteration |
| Logpoint | “Add Logpoint”, for example price={item.price} | You want a log without editing the code |
| Exception breakpoints | Breakpoints panel → “Caught/Uncaught Exceptions” | Pause exactly where an error is thrown |
💡 Tip: Turn on “Uncaught Exceptions” in the Breakpoints panel. The debugger then stops at the line that throws, with all local variables visible, which is often faster than reading the stack trace.
launch.json for repeatable debug sessions
Save a debug configuration so the whole team starts the debugger the same way (Run and Debug → create a launch.json file):
📄 .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug current file",
"program": "${file}",
"skipFiles": ["<node_internals>/**"]
},
{
"type": "node",
"request": "launch",
"name": "Debug npm test",
"runtimeExecutable": "npm",
"runtimeArgs": ["test"],
"env": { "NODE_DEBUG": "orders" },
"skipFiles": ["<node_internals>/**", "**/node_modules/**"]
}
]
}
skipFiles stops the debugger from stepping into Node.js internals and libraries. VS Code also offers a JavaScript Debug Terminal (Command Palette → “Debug: JavaScript Debug Terminal”): any node or npm command run in it starts with the debugger attached.
🛰️ node –inspect and Chrome DevTools
Node.js can be debugged with Chrome’s DevTools too. Start the script with an inspector flag:
⌨️ Terminal
node --inspect-brk debug-me.js
🖥️ Output (the ID changes every run)
Debugger listening on ws://127.0.0.1:9229/3052d451-479b-40b1-b568-a582926a527c
For help, see: https://nodejs.org/learn/getting-started/debugging
--inspectstarts the program and lets a debugger attach;--inspect-brkalso pauses on the first line, so you have time to attach before anything runs.- In Chrome, open
chrome://inspectand click inspect under your script (or “Open dedicated DevTools for Node”). - You get the full Sources panel: breakpoints, stepping, scope variables, the console, and the Memory and Performance profilers.
- The inspector listens on
127.0.0.1only by default. Never expose it on a public network: anyone who connects can run code in your process.
The terminal-only debugger node inspect file.js (commands cont, next, step, repl) is handy on servers without a GUI.
🌐 Debugging Code in the Browser
For JavaScript running in a web page, use the browser’s DevTools (F12) → Sources panel:
| Tool | What it does |
|---|---|
| Line breakpoints | Click a line number in a script, exactly as in VS Code |
debugger; statement | Pauses at that line whenever DevTools is open |
| XHR/fetch breakpoints | Pause when a request URL contains some text, such as /api/orders |
| DOM breakpoints | Right-click an element in Elements → Break on → subtree modifications / attribute modifications / node removal |
| Event listener breakpoints | Pause on any click, keydown, submit… event |
| Pause on exceptions | The pause icon in the Breakpoints pane, like VS Code’s exception breakpoints |
| Network panel | Inspect every request and response: status, headers, payload, timing |
Source maps connect the bundled, minified code the browser runs to your original source files (or TypeScript). With source maps, breakpoints and stack traces show your real file names and lines. In Node.js, node --enable-source-maps applies them to stack traces of compiled code.
💡 Tip: A DOM breakpoint on “subtree modifications” is the quickest way to find which script keeps changing an element, for example a value that a test fills in and something else overwrites a moment later.
🎭 Debugging Playwright Tests
Playwright includes dedicated tools for failing tests. These are the ones you will use most:
⌨️ Terminal
# Run with the Playwright Inspector: step through actions, see locators highlighted
npx playwright test login.spec.ts --debug
# UI mode: watch mode, time-travel through every step, pick locators
npx playwright test --ui
# Record a trace for each test and open it after a failure
npx playwright test --trace on
npx playwright show-trace test-results/login-chromium/trace.zip
# Print Playwright's API logs (bash/zsh syntax)
DEBUG=pw:api npx playwright test login.spec.ts
📄 checkout.spec.ts (Playwright, for reference)
import { test, expect } from "@playwright/test";
test("checkout", async ({ page }) => {
await page.goto("/cart");
await page.pause(); // opens the Inspector here, like a breakpoint
await page.getByRole("button", { name: "Checkout" }).click();
await expect(page).toHaveURL(/\/checkout/);
});
- The trace viewer shows every action with a DOM snapshot before and after, the console, network requests and the source line, which makes CI-only failures debuggable after the fact.
- VS Code’s Playwright extension adds a “Debug Test” button next to each test, so normal breakpoints work in test code.
- The Playwright course covers these in detail: Playwright Debugging and Trace Viewer.
🧪 Tester Scenario: Isolate a Bug by Halving the Data
A total is wrong, and the input has hundreds of rows. Instead of reading them all, check halves until you find the bad row, a technique called bisection (the same idea as git bisect for finding the commit that introduced a bug):
📄 bisect.js
const rows = Array.from({ length: 200 }, (_, i) => ({ id: i + 1, price: 10 }));
rows[137].price = "10"; // the hidden bug: a string price
const isGood = (subset) => subset.every((r) => typeof r.price === "number");
function bisect(list) {
let lo = 0, hi = list.length, steps = 0;
while (hi - lo > 1) {
steps++;
const mid = Math.floor((lo + hi) / 2);
if (isGood(list.slice(lo, mid))) lo = mid; // bug is in the second half
else hi = mid; // bug is in the first half
}
return { row: list[lo], steps };
}
const total = rows.reduce((sum, r) => sum + r.price, 0);
console.log("total looks wrong:", typeof total, String(total).slice(0, 25) + "...");
console.log(bisect(rows));
⌨️ Terminal
node bisect.js
🖥️ Output
total looks wrong: string 1370101010101010101010101...
{ row: { id: 138, price: '10' }, steps: 7 }
Seven checks found the one bad row out of 200. The broken total itself is a clue: + with a string switched to string concatenation from that row on (see the Type Conversion lesson).
Checklist of common JavaScript bugs
| Symptom | Usual cause |
|---|---|
Cannot read properties of undefined | Missing data, wrong property name, empty array, or a missing await (you have a Promise) |
x is not a function | Typo, wrong import, a getter called with (), or this lost in a callback |
Numbers join like "1020" | A string from the UI or JSON was not converted |
| Test passes but should fail | Missing await before an assertion, swallowed error, or every on an empty list |
| Works locally, fails in CI | Timing, different data, environment variables, time zone or locale |
| Value changes unexpectedly | Shared object or array mutated somewhere else (reference, not copy) |
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Read this stack trace and say which function and line to look at first, and why.
TypeError: Cannot read properties of undefined (reading 'email')
at formatUser (/app/helpers.js:12:21)
at Array.map (<anonymous>)
at renderUsers (/app/report.js:30:18)
at main (/app/index.js:8:3)Show answer
Start at formatUser in helpers.js, line 12, column 21: it is the top frame in your own code, where something was undefined when .email was read. The next frames show it ran inside an Array.map called from renderUsers, so one of the items passed to map (or a nested object inside it) was missing.
Q2. Print the type of every value in { id: "7", total: 1299, paid: "false", items: [] } to find suspicious types.
Show answer
📄 practice2.js
const order = { id: "7", total: 1299, paid: "false", items: [] };
for (const [key, value] of Object.entries(order)) {
console.log(key.padEnd(6), Array.isArray(value) ? "array" : typeof value, JSON.stringify(value));
}🖥️ Output
id string "7"
total number 1299
paid string "false"
items array []id and paid are strings: "false" is truthy, a classic bug if the code does if (order.paid).
Q3. Add a debug log that prints only when the environment variable DEBUG_TEST is set to 1.
Show answer
📄 practice3.js
const debug = (...args) => {
if (process.env.DEBUG_TEST === "1") console.log("[debug]", ...args);
};
debug("loaded 3 users"); // silent unless DEBUG_TEST=1
console.log("test finished");🖥️ Output
test finishedRun DEBUG_TEST=1 node practice3.js (bash) or set $env:DEBUG_TEST="1" first in PowerShell to see the debug line.
Q4. Which VS Code feature would you use in each case? (a) Pause only when user.role === "admin". (b) Log a value at a line without editing the file. (c) Stop exactly where any error is thrown.
Show answer
(a) A conditional breakpoint with the expression user.role === "admin". (b) A logpoint. (c) The “Uncaught Exceptions” (or “Caught Exceptions”) option in the Breakpoints panel.
Q5. This async function loses the error. Find the bug and fix it so the caller’s catch runs.
async function save() {
throw new Error("save failed");
}
async function main() {
try {
save();
console.log("saved?");
} catch (e) {
console.log("caught:", e.message);
}
}
main().catch(() => {});Show answer
📄 practice5.js
async function save() {
throw new Error("save failed");
}
async function main() {
try {
await save();
console.log("saved?");
} catch (e) {
console.log("caught:", e.message);
}
}
main();🖥️ Output
caught: save failedWithout await, save() returns a rejected promise and the try block finishes immediately, so “saved?” is printed and the rejection is never caught there.
Q6. Use bisection to find the first test ID in 1–64 at which a (simulated) build starts failing, where builds from ID 41 onwards fail.
Show answer
📄 practice6.js
const fails = (id) => id >= 41; // simulated: unknown to the searcher
let lo = 1, hi = 64, checks = 0;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
checks++;
if (fails(mid)) hi = mid; else lo = mid + 1;
}
console.log(`first failing ID: ${lo} after ${checks} checks`);🖥️ Output
first failing ID: 41 after 6 checks🧠 MCQ Quiz: Debugging in VS Code and DevTools
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What is the first step when debugging?Answer: Reproduce the problem reliably. Without reproduction you cannot confirm the cause or the fix.
- In a stack trace, which line is the most recent call?Answer: The first line after the error message. Read from the top; find the first frame in your code.
- What does a conditional breakpoint do?Answer: Pauses only when an expression is true. Ideal for one bad item inside a large loop.
- What is a logpoint?Answer: A breakpoint that logs a message instead of pausing. No code change or cleanup is needed.
- What does
node --inspect-brk app.jsdo?Answer: Starts the debugger and pauses on the first line. Attach from chrome://inspect or VS Code. - Which VS Code key steps into a function call?Answer: F11. F10 steps over; Shift+F11 steps out.
- Which Playwright command opens the Inspector to step through a test?Answer: npx playwright test –debug. page.pause() opens it at a specific point.
- What do source maps do?Answer: Map compiled or minified code back to the original source lines. Use node –enable-source-maps for Node.js stack traces.
- Why do async stack traces sometimes miss frames?Answer: A promise in the chain was not awaited. Consistently awaiting keeps the async chain.
- What is the fastest way to find one bad row among 1,000?Answer: Bisection: check halves repeatedly. About 10 checks for 1,000 rows.
💼 Interview Questions and Answers
Q1. Walk me through how you debug a failing automated test.
- Read the failure: error type, message, and the first stack frame in test or framework code.
- Reproduce it: run only that test locally (headed, same browser, same data); check whether it fails every time or intermittently.
- Inspect evidence: screenshot, video, trace (Playwright trace viewer), console and network logs.
- Form and test a hypothesis with breakpoints or targeted logs: wrong locator, timing, data, environment, or a real product bug.
- Fix the root cause (or raise a bug with evidence), then rerun several times, and in CI, to confirm it is stable.
Q2. What is the difference between console.log debugging and using a debugger?
Logging is quick and works anywhere (including CI), but you must decide in advance what to print and rerun for each new question. A debugger pauses execution so you can inspect every variable, the call stack and evaluate expressions live, step line by line, and use conditional breakpoints, without editing code. Use logs for CI and distributed timing issues; use the debugger for logic bugs you can reproduce locally.
Q3. A test passes locally but fails in CI. How do you approach it?
Collect artefacts from CI (trace, screenshots, logs, environment details). Compare environments: browser and Node.js versions, screen size, headless mode, time zone and locale, environment variables and test data, CPU speed (timing). Reproduce CI conditions locally (headless, same Docker image, slowed CPU, parallel workers). Typical causes are missing waits or assertions that are not web-first, shared state between parallel tests, and data or configuration differences.
Q4. How do you debug a Node.js script with Chrome DevTools?
Run it with node --inspect-brk script.js (pause on the first line) or --inspect (attach while running). Open chrome://inspect, click inspect under the target, then use the Sources panel to set breakpoints, step, inspect scope and evaluate code; the Memory and Performance tabs profile the process. Keep the inspector bound to localhost.
❓ Frequently Asked Questions
🤔 How do I debug JavaScript in VS Code without configuration?
Open the file and press F5, then choose Node.js, or open a JavaScript Debug Terminal and run your usual command. Breakpoints work immediately.
🤔 What is the debugger statement?
Writing debugger; in code pauses execution at that line whenever a debugger is attached (VS Code, Chrome DevTools, node inspect). Without a debugger it does nothing. Remove it before committing.
🤔 How can I debug a test that only fails sometimes?
Run it many times (Playwright --repeat-each=20), record traces on failure, and look for timing assumptions, shared state and test-order dependencies.
🤔 Do breakpoints work in TypeScript files?
Yes, when source maps are available. Playwright and modern tools generate them automatically.
🏁 Summary
- Debug with a process: reproduce, read the error, isolate, test a hypothesis, fix the cause and add a check.
- Read stack traces from the top and start at the first frame in your code; keep
awaitconsistent for useful async traces. - Use targeted, labelled logs and switchable debug logging; inspect types as well as values.
- VS Code breakpoints, conditional breakpoints, logpoints, exception breakpoints and watches find logic bugs fast;
node --inspectconnects Chrome DevTools. - For browser code use the Sources panel and source maps; for Playwright use
--debug,--ui,page.pause()and the trace viewer.
Next up is Lesson 46: Event Loop, coming soon. See the course syllabus for what is already available. This completes Module 9. Module 10 covers asynchronous JavaScript: the event loop, promises and async/await.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in