Debugging Detective Laboratory
Realistic bugs to investigate: reproduce the problem, read the evidence, form a hypothesis, repair the code and verify the fix with automated checks. 50 cases are open now.
How to investigate: reproduce → locate → inspect → change one thing → verify. Resist replacing the code wholesale (with AI or otherwise): the goal is to find the cause.
The welcome banner never appears
The store's start-up script should print a welcome banner and today's special. When it runs, the console shows only a red error and neither line appears, not even the second line, which looks correct.
console.log("Welcome to the JavaScript store);
console.log("Today's special: 3 for 2");
The order total says 2540
A checkout script copies the book price from a form field and adds the shipping cost. Customers see an order total of 2540 instead of 65.
const bookPrice = "25"; // copied from a form field
const shipping = 40;
const total = bookPrice + shipping;
console.log("Order total:", total);
The average score is 180
A grade report should show the average of three quiz scores (70, 80 and 90). It prints 180, which is higher than any single score.
const quiz1 = 70;
const quiz2 = 80;
const quiz3 = 90;
const average = quiz1 + quiz2 + quiz3 / 3;
console.log("Average score:", average);
The cart log shows [object Object]
A developer logs the cart to check its contents, but the console only shows Cart: [object Object], which hides the data needed to debug.
const cart = { items: 3, total: 135 };
console.log("Cart: " + cart);
console.log("Total:", cart.total);
total is not defined
An order summary prints the item count and then crashes with ReferenceError: total is not defined, even though the developer is sure they created the total.
const Total = 135;
const itemCount = 6;
console.log("Items:", itemCount);
console.log("Total:", total);
The loyalty points never increase
A loyalty program should add 50 points per purchase. After three purchases the balance still shows 100.
let points = 100;
points + 50;
points + 50;
points + 50;
console.log("Points:", points);
The order summary runs words together
The checkout summary should read Ada ordered 3 items for 45 dollars. Customers see Adaordered3itemsfor45dollars.
const customer = "Ada";
const count = 3;
const total = 45;
const summary = customer + "ordered" + count + "items" + "for" + total + "dollars";
console.log(summary);
The discounted price shows NaN
A sale page should show the price after a 20% discount: 80. It shows NaN.
const price = 100;
const discountPercent = "twenty";
const salePrice = price - price * discountPercent / 100;
console.log("Sale price:", salePrice);
Free samples turn into one item
A sample order has a quantity of 0 (the customer removed it). The packing list should say Quantity: 0, but it shows Quantity: 1.
const quantity = 0;
const shown = quantity || 1;
console.log("Quantity:", shown);
The booking shows 2010 tickets
A booking form adds adult and child tickets. A family of 20 adults and 10 children should see 30 tickets, but the summary says 2010.
const adults = "20"; // from an input field
const children = "10"; // from an input field
const total = adults + children;
console.log("Total tickets:", total);
A valid promo code is rejected
Shoppers who type save10 get "Invalid code" even though SAVE10 is a valid promotion.
const validCode = "SAVE10";
const typed = " save10 ";
const accepted = typed === validCode;
console.log(accepted ? "Code accepted" : "Invalid code");
Out-of-stock items ship free
Free shipping should apply only to in-stock items for members or orders of $50 or more. A member's out-of-stock order is getting free shipping.
// Rule: (member OR total at least 50) AND in stock
const isMember = true;
const total = 30;
const inStock = false;
const freeShipping = isMember || total >= 50 && inStock;
console.log("Free shipping:", freeShipping);
Every customer is Bronze
A loyalty program has Gold (1000+ points), Silver (500+) and Bronze (100+). A customer with 1,250 points is shown as Bronze.
const points = 1250;
let tier = "None";
if (points >= 100) {
tier = "Bronze";
} else if (points >= 500) {
tier = "Silver";
} else if (points >= 1000) {
tier = "Gold";
}
console.log("Tier:", tier);
Silver members get two discounts
Silver members should get 10% off. The checkout applies 10% and then another 5%, and the final price is too low.
const tier = "silver";
let price = 100;
switch (tier) {
case "gold":
price = price * 0.8;
case "silver":
price = price * 0.9;
case "bronze":
price = price * 0.95;
}
console.log("Price:", price);
Exactly 60 minutes is charged as 2 hours
Parking costs $3 per started hour. A driver who parks for exactly 60 minutes is charged $6.
const RATE = 3;
const minutes = 60;
const hours = Math.floor(minutes / 60) + 1;
console.log(`Fee: $${hours * RATE}`);
The receipt skips the first item
A three-item receipt only shows two items and the total is too low.
const prices = [2, 3, 4];
let total = 0;
for (let i = 1; i < prices.length; i++) {
total += prices[i];
}
console.log(`Total: $${total}`);
The savings plan stops one month early
The app says the $500 goal is reached, but the balance it prints is below $500.
const GOAL = 500;
let balance = 0;
let month = 0;
while (balance < GOAL - 100) {
balance += 100;
month++;
}
console.log(`Month ${month}: $${balance}`);
The sales report stops at a cancelled order
The daily revenue is far too low. Orders after the first cancelled one are never counted.
const orders = [
{ total: 40, cancelled: false },
{ total: 25, cancelled: true },
{ total: 30, cancelled: false },
{ total: 25, cancelled: false }
];
let revenue = 0;
for (const order of orders) {
if (order.cancelled) break;
revenue += order.total;
}
console.log("Revenue:", revenue);
Each store's total includes the stores before it
The weekly report shows the right total for Store 1, but every later store is far too high.
const sales = [[4, 6], [1, 5]];
let rowTotal = 0;
for (let r = 0; r < sales.length; r++) {
for (let c = 0; c < sales[r].length; c++) {
rowTotal += sales[r][c];
}
console.log(`Store ${r + 1}: ${rowTotal}`);
}
The average shows NaN for a new user
A new user with no workouts sees Average: NaN minutes on their dashboard.
const workouts = [];
let sum = 0;
for (const minutes of workouts) {
sum += minutes;
}
const average = sum / workouts.length;
console.log(`Average: ${average} minutes`);
The footer appears before the items
Receipts show the thank-you footer at the top instead of after the items.
function printFooter() {
console.log("Thank you!");
}
function printItems() {
printFooter();
console.log("Tea");
console.log("Cake");
}
printItems();
The discount argument is ignored
Calling finalPrice(80, 0.25) still charges the default 10% discount.
function finalPrice(price, rate = 0.1) {
const discount = 0.1;
const final = price * (1 - discount);
console.log(`Final: $${final}`);
return final;
}
const result = finalPrice(80, 0.25);
The checkout total is NaN
The checkout prints the subtotal correctly, then shows Pay: $NaN.
function subtotal(prices) {
let sum = 0;
for (const p of prices) sum += p;
console.log("Subtotal:", sum);
}
const SHIPPING = 5;
const pay = subtotal([12, 8]) + SHIPPING;
console.log(`Pay: $${pay}`);
New cart items are undefined
A helper that creates cart items returns undefined, so the cart shows Item: undefined.
const createItem = (name) => { name: name };
const item = createItem("Mug");
console.log(`Item: ${item?.name}`);
The tip is added twice
Each helper works on its own, but the combined calculator charges $60 on a $40 bill with a 25% tip.
const tipFor = (bill, percent) => bill * percent / 100;
const totalWithTip = (bill, percent) => bill + tipFor(bill, percent);
function checkout(bill, percent) {
const tip = tipFor(bill, percent);
const total = totalWithTip(bill, percent) + tip;
return `Total: $${total.toFixed(2)}`;
}
const output = checkout(40, 25);
console.log(output);
The leaderboard shows second place as the winner
The scores are already sorted from highest to lowest, but the banner names the second-place player as the winner.
const players = ["Ada", "Grace", "Linus"];
const winner = players[1];
console.log(`Winner: ${winner}`);
Showing a preview empties the cart
After the cart preview shows the first two items, the cart total only counts the last item.
const cart = ["Tea", "Mug", "Cake"];
const preview = cart.splice(0, 2);
console.log("Preview:", preview.join(", "));
console.log("Items in cart:", cart.length);
"Cheapest first" shows the most expensive item
Prices of 8, 75 and 120 are sorted "cheapest first", but the first card shows $120.
const prices = [75, 8, 120];
const sorted = [...prices].sort();
console.log(`Cheapest: $${sorted[0]}`);
Removing expired coupons skips some
Two expired coupons are next to each other, and only one of them is removed.
const coupons = [
{ code: "SAVE5", expired: false },
{ code: "OLD1", expired: true },
{ code: "OLD2", expired: true },
{ code: "FREESHIP", expired: false }
];
for (let i = 0; i < coupons.length; i++) {
if (coupons[i].expired) coupons.splice(i, 1);
}
const active = [];
for (const c of coupons) active.push(c.code);
console.log("Active:", active.join(", "));
Deleting an unknown contact deletes the last one
A stale button tries to delete contact 7, which no longer exists, and the last contact in the list disappears.
const contacts = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
{ id: 3, name: "Linus" }
];
function removeContact(id) {
const i = contacts.findIndex((c) => c.id === id);
contacts.splice(i, 1);
}
removeContact(7);
console.log("Contacts:", contacts.map((c) => c.name).join(", "));
The basket total stays at zero
The basket has three items worth $18, but the total shown is 0.
const basket = [5, 9, 4];
let total = 0;
basket.forEach((price) => {
let total = 0;
total += price;
});
console.log("Total:", total);
Showing sale prices changes the catalogue
After showing a 50% sale view, the normal catalogue also shows half prices.
const catalogue = [{ name: "Mug", price: 20 }];
const sale = catalogue.map((p) => {
p.price = p.price / 2;
return p;
});
console.log("Sale:", sale[0].price);
console.log("Normal:", catalogue[0].price);
Free items disappear from the order
A promotion adds a free tote bag (price 0), but it vanishes from the order list.
const lines = [
{ name: "Mug", price: 8 },
{ name: "Tote", price: 0 },
{ name: "Tea", price: 5 },
{ name: "Unknown", price: undefined }
];
const valid = lines.filter((l) => l.price);
console.log("Lines:", valid.map((l) => l.name).join(", "));
The average rating is far too high
Reviews of 4, 5 and 3 stars should average 4, but the product page shows 5.33.
const reviews = [{ stars: 4 }, { stars: 5 }, { stars: 3 }];
const sum = reviews.reduce((acc, r) => acc + r.stars, reviews.length);
const average = sum / reviews.length;
console.log(`Average: ${average.toFixed(2)}`);
The clearance total includes full-price items
The clearance report should total only items marked clearance, but it shows a total of 0.
const items = [
{ name: "Lamp", price: 30, clearance: false },
{ name: "Vase", price: 20, clearance: true },
{ name: "Rug", price: 15, clearance: true }
];
const total = items
.map((i) => i.price)
.filter((i) => i.clearance)
.reduce((sum, p) => sum + p, 0);
console.log("Clearance total:", total);
Loyalty points never update
After a purchase the customer should have 150 points, but the screen still shows 100.
const customer = { name: "Ada", points: 100 };
customer.point = customer.points + 50;
console.log("Points:", customer.points);
The cart total is NaN when used as a callback
cart.total() works on its own, but passing cart.total to a helper that calls it prints NaN.
const cart = {
prices: [10, 20],
total() {
let sum = 0;
for (const p of this?.prices ?? [NaN]) sum += p;
return sum;
}
};
function show(getTotal) {
console.log("Total:", getTotal());
}
show(cart.total);
Changing the theme deletes the alert settings
After switching to dark mode, the user's alert preferences are gone.
const settings = { prefs: { theme: "light", alerts: true } };
function setTheme(theme) {
settings.prefs = { theme };
}
setTheme("dark");
console.log(settings.prefs.theme, settings.prefs.alerts);
Every invoice ends up with the same customer
Two invoices are created from one template, but after filling the second, both show Grace as the customer.
const template = { number: 0, customer: { name: "" } };
function newInvoice(n, name) {
const inv = { ...template, number: n };
inv.customer.name = name;
return inv;
}
const inv1 = newInvoice(1, "Ada");
const inv2 = newInvoice(2, "Grace");
console.log(inv1.customer.name, inv2.customer.name);
Renamed products still show old names in orders
The "Mug" product was renamed "Travel Mug", but order history still shows "Mug".
const products = [{ id: "p1", name: "Mug" }];
const orders = [{ id: "o1", lines: [{ productId: "p1", name: "Mug", qty: 2 }] }];
products[0].name = "Travel Mug";
function lineLabel(line) {
return `${line.name} x${line.qty}`;
}
const label = lineLabel(orders[0].lines[0]);
console.log(label);
The default theme never applies
Users without a saved theme should get "light", but the app shows "Theme: null".
const saved = { theme: null, fontSize: 14 };
const { theme = "light", fontSize } = saved;
console.log(`Theme: ${theme}`);
Undo history changes when the draft changes
The editor saves a snapshot before editing, but the snapshot changes too, so undo shows the edited tags.
const draft = { title: "Report", tags: ["draft"] };
const snapshot = { ...draft };
draft.tags.push("urgent");
console.log(`Snapshot tags: ${snapshot.tags}`);
Optional chaining in the wrong place
The team added ?. to stop a crash for guests, but the receipt still throws a TypeError for guest orders.
const order = { id: 11, total: 18 };
const name = order?.customer.name ?? "Guest";
console.log(`Receipt for ${name}`);
Free shipping gets charged
Some products have a shipping cost of 0, but checkout charges the standard 4.99 for them.
const product = { name: "Ebook", shipping: 0 };
function shippingFor(p) {
return p.shipping || 4.99;
}
const cost = shippingFor(product);
console.log(`${product.name} shipping: ${cost}`);
Cart quantities are always undefined
The cart stores quantities in a Map, but the summary shows "Mug: undefined" after adding two mugs.
const cart = new Map();
function add(name) {
cart[name] = (cart.get(name) ?? 0) + 1;
}
add("Mug");
add("Mug");
console.log(`Mug: ${cart.get("Mug")}`);
The counter shows 1 every time
A like button should count up, but after three clicks the counter still shows 1.
function like() {
let count = 0;
count += 1;
return count;
}
like();
like();
const shown = like();
console.log(`Likes: ${shown}`);
The helper uses the wrong exchange rate
The conversion for euros should use the euro rate set in convertToEuro, but the result uses the default rate of 1.
const rate = 1;
function applyRate(amount) {
return Math.round(amount * rate);
}
function convertToEuro(amount) {
const rate = 0.92;
return `${amount} -> ${applyRate(amount)}`;
}
const line = convertToEuro(100);
console.log(line);
Every tab opens the last panel
Three tab handlers are created in a loop. Clicking the first tab should open panel 0, but every handler opens panel 3, which does not exist.
const handlers = [];
for (var i = 0; i < 3; i++) {
handlers.push(() => `open ${i}`);
}
const results = handlers.map((h) => h());
console.log(results.join(", "));
The page fails after moving start-up code
After moving start() to the top of the file, loading fails with "Cannot access 'TITLE' before initialization".
const message = start();
function start() {
return `Welcome to ${TITLE}`;
}
const TITLE = "Shop";
console.log(message);
Folder size calculation overflows the stack
Calculating the size of a folder tree throws RangeError: Maximum call stack size exceeded instead of returning 60.
const root = { size: 10, children: [{ size: 20, children: [] }, { size: 30, children: [] }] };
function totalSize(folder) {
let sum = folder.size;
for (const child of folder.children) sum += totalSize(folder);
return sum;
}
let total;
try { total = totalSize(root); } catch (e) { total = e.name; }
console.log(`Total: ${total}`);