Explain it simply
Explain it simply
Debugging is detective work. "The total should be 35 but it shows 10520" is the crime scene. A good detective does not arrest the first person they see; they collect clues and rebuild what happened, one step at a time.
In JavaScript, your clue-gathering tools are printing methods like console.log() and console.table(), the debugger statement that pauses code mid-run, and breakpoints in the browser DevTools. While the code is paused you can look at every variable's value directly.
Problem → Why → Solution
The problem: hiding the symptom does not remove the bug
Say a shopping-cart total shows "10520" when it should be 35. A developer in a hurry wraps the display line in parseInt(); the result is still 10520 and now nobody knows what the change was for. Another developer special-cases the "Pen" item and skips it, which works today and breaks again tomorrow when a new item arrives with a text price.
// Symptom: the page shows "Total: 10520" instead of 35
function total(items) {
let sum = 0;
for (const item of items) sum += item.price;
return sum;
}
// "Fix" 1: patch the display line (still 10520)
console.log("Total:", parseInt(total(cart)));
// "Fix" 2: skip the item that looked strange (breaks on the next one)
const safeCart = cart.filter((item) => item.name !== "Pen");Why does guess-fixing fail?
The place where a symptom appears is rarely the place where the bug lives. Here the culprit is not the display line: a "5" string arrived from a form and the + operator joined text instead of adding numbers. Fixing without evidence just moves the error somewhere else. Only tracing the bad value backward to its source and fixing it there removes the bug.
Core concept: debugging is a process
Experienced developers find bugs quickly not because they are lucky but because they follow the same steps every time. Each step narrows the area you still have to search.
1. Reproduce
Make the bug happen on demand and write down the exact input or click sequence. A bug you cannot reproduce is a bug you can never prove fixed.
2. Isolate
Remove pieces of the input until you have the smallest case that still fails, a minimal reproducible case. If three items trigger it, take them out one by one.
3. Hypothesise and gather evidence
Form one guess, such as "one price is a string", then log or pause on exactly the values that would confirm or reject it.
4. Fix and add a regression check
Fix the cause, then add a check or test that fails if the bug ever comes back, and delete the temporary logs.
When collecting evidence, the most useful log line carries a label, the value and its typeof. console.log(sum) shows only 105, while console.log("after Pen:", sum, typeof sum) shows "after Pen: 105 string" and gives the bug away immediately. console.table() lays an array of objects out as a table, and console.trace() prints the call stack showing who called the current function.
When logs pile up, a breakpoint is cleaner. Writing debugger; in your code pauses execution on that line whenever DevTools is open (with DevTools closed it does nothing). While paused, the Scope panel shows local variables, the Call Stack panel shows how you got there, Watch shows expressions you choose, and step over / step into move one line at a time. In Node.js, run node --inspect and attach Chrome DevTools to get the same tools.
- Reproduce the bug on demand
- Shrink to the smallest failing input
- Log or pause on value + typeof
- Fix where the bad value enters
- Add a regression check
Start where the symptom shows and walk the value backward; the first place it goes wrong is where the bug lives.
General pattern
console.log("label:", value, typeof value); // value + its type
console.table(arrayOfObjects); // rows and columns
console.trace("how did we get here?"); // call stack (stderr)
console.error("something failed:", error); // error stream
function suspect(input) {
debugger; // pauses here while DevTools is open
return transform(input);
}Give every log a label so you can tell lines apart when the output grows. console.trace() and console.error() write to stderr, so in Node.js they go to a different stream from normal stdout output. The debugger statement only does something while DevTools (or node --inspect) is attached.
Example: debugging a cart total of 10520
This example walks the whole process in a form you can run in Node.js. First it reproduces the bug, then it logs the value and type at every loop step to find where a number turns into a string, and finally it fixes the cause and confirms the fix with a check.
// The bug report: "the cart total is 10520, but it should be 35"
const cart = [
{ name: "Notebook", price: 10 },
{ name: "Pen", price: "5" }, // this price came from a form field as text
{ name: "Bag", price: 20 },
];
function total(items) {
let sum = 0;
for (const item of items) {
sum += item.price;
}
return sum;
}
console.log("Total:", total(cart));
// Gather evidence: log every intermediate value together with its type
const DEBUG = true;
function debugLog(label, value) {
if (DEBUG) console.log(`[debug] ${label}:`, value, `(${typeof value})`);
}
function totalTraced(items) {
let sum = 0;
for (const item of items) {
sum += item.price;
debugLog(`after ${item.name}`, sum);
}
return sum;
}
totalTraced(cart);
// Fix the cause (text prices), then prove it with a check
function fixedTotal(items) {
return items.reduce((sum, item) => sum + Number(item.price), 0);
}
console.log("Fixed total:", fixedTotal(cart));
console.log("Regression check:", fixedTotal(cart) === 35 ? "PASS" : "FAIL");Code breakdown
- Reproduce
console.log("Total:", total(cart));Before changing anything, make the bug happen on demand. The output is 10520, matching the bug report.
- Conditional logging
if (DEBUG) console.log(`[debug] ${label}:`, value, `(${typeof value})`);One DEBUG flag switches every debug log on or off in one place. Printing typeof alongside the value is the key that exposes this bug.
- Evidence inside the loop
debugLog(`after ${item.name}`, sum);Logging sum after each item pinpoints the moment: 10 (number) after Notebook, then 105 (string) after Pen, so Pen's price is the culprit.
- Root cause
{ name: "Pen", price: "5" }, // this price came from a form field as textIn 10 + "5" one operand is a string, so + concatenates instead of adding and produces "105"; then "105" + 20 becomes "10520".
- Fix at the source
return items.reduce((sum, item) => sum + Number(item.price), 0);Converting each price with Number() before adding gives 35. In a real app, convert even earlier, at the point where form data enters the program.
- Regression check
console.log("Regression check:", fixedTotal(cart) === 35 ? "PASS" : "FAIL");The input that caused the bug and the correct answer are kept as a check. In a real project this becomes a unit test.
Total: 10520
[debug] after Notebook: 10 (number)
[debug] after Pen: 105 (string)
[debug] after Bag: 10520 (string)
Fixed total: 35
Regression check: PASSWhich tool to reach for
| Tool | Best for |
|---|---|
| console.log(label, value) | A quick look at one or two values |
| console.table(rows) | Comparing an array of objects as a table |
| console.trace() | Finding out who called a function |
| debugger / breakpoint | Watching many variables line by line |
| Network panel | Checking API requests and responses |
Conditional breakpoints
If a loop runs 1,000 times and only one item is wrong, right-click the line number in DevTools and add a condition such as typeof item.price === "string". The debugger then pauses only when the condition is true.
In real projects
Where this shows up in real projects
In real projects, bug reports arrive vague: "the order page total is wrong". The first job is to ask which user and which cart, then reproduce it locally. Next, the Network panel shows the JSON the API returned, so you can check whether prices are numbers or strings and decide right there whether the problem lives on the server or in the browser.
A habit many teams share is writing a failing test before the fix: the bug is recorded as code, and the test turns green once the fix lands. Production servers cannot be paused at a breakpoint, so teams rely on structured logs carrying a request id or user id, plus error-monitoring tools that collect stack traces. Delete temporary console.log calls before you commit; ESLint's no-console and no-debugger rules catch the ones you forget.
Common mistakes
Common mistakes
1. Scattering unlabelled logs
Ten bare console.log(x) calls print a column of 10, 105, undefined with no clue where each came from. Give each log a label such as "after Pen:" and include typeof.
2. Logging an object that changes later
In the browser console, expanding a logged object later can show its current contents, not what it held at log time. When you need a snapshot, log JSON.stringify(obj) or structuredClone(obj) instead.
3. Declaring victory after one passing sample
Making the one failing input pass is not enough. Try boundary and invalid inputs too, such as an empty array or a price of "abc" (Number() turns it into NaN), or you may have hidden a new bug behind the fix.
Best practices
Best practices
- Test one hypothesis at a time; change several things at once and you cannot tell which one fixed it.
- Keep short notes of what you tried and what you saw, so a long hunt does not go in circles.
- Commit a test that would have caught the bug together with every fix.
- Read the whole error message and stack trace, not just the top line; the first frame inside your own code is where to start looking.
Mini challenge
Mini challenge: debug an average that returns NaN
averageScore([80, 90, 70]) should return 80 but returns NaN. Follow the process to find and fix the bug, then write three regression checks.
- Find the bug by logging i and scores[i] with labels inside the loop
- Fix the loop condition
- Return 0 for an empty array instead of NaN
- Print three PASS/FAIL lines with a check(label, actual, expected) helper
// Reported: averageScore([80, 90, 70]) returns NaN instead of 80
function averageScore(scores) {
let sum = 0;
for (let i = 0; i <= scores.length; i++) {
// TODO: log a labelled i, scores[i] and typeof sum to gather evidence
sum += scores[i];
}
return sum / scores.length;
}
function check(label, actual, expected) {
// TODO: print "PASS label: ..." or "FAIL label: ..."
}
// TODO: after fixing, check [80, 90, 70] -> 80, [55] -> 55, [] -> 0Expected: All three checks pass: PASS three scores: got 80, expected 80 PASS one score: got 55, expected 55 PASS empty list: got 0, expected 0
Show hint
An array of three items only has indexes 0, 1 and 2. Think about what scores[3] is when i reaches 3, and what 240 plus that value gives. For an empty array, 0 / 0 is NaN as well.
Show solution
// Evidence: with i <= scores.length the loop read scores[3], which is
// undefined, and 240 + undefined is NaN. An empty array gave 0 / 0 = NaN.
function averageScore(scores) {
if (scores.length === 0) return 0;
let sum = 0;
for (let i = 0; i < scores.length; i++) {
sum += scores[i];
}
return sum / scores.length;
}
function check(label, actual, expected) {
const status = actual === expected ? "PASS" : "FAIL";
console.log(`${status} ${label}: got ${actual}, expected ${expected}`);
}
check("three scores", averageScore([80, 90, 70]), 80);
check("one score", averageScore([55]), 55);
check("empty list", averageScore([]), 0);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Debugging is a process: reproduce, isolate, hypothesise, gather evidence, fix, add a regression check.
- Log a label, the value and its typeof so type bugs show up immediately.
- console.table shows object arrays as a table, console.trace shows the call stack, and debugger or breakpoints pause code so you can inspect variables.
- Fix where the bad value enters, not where the symptom appears, and remove temporary logs afterwards.
MDN — JavaScript Guide — MDN Web Docs