Learn
🤖 AI Hub 📰 News 📖 Dictionary 🧰 Resources
Grow
💼 Jobs 🚀 Community 🏆 Challenges
Explore by Stage
🌑 Zero 📚 Learn 🔧 Practice 🏗 Build 🚀 Launch 💰 Earn
Account
Login Sign Up
🏗️HTML 🎨CSS ⚡JavaScript 🐙Git & GitHub ⚛️React Soon 📘TypeScript Soon 🐍Python 🗄️Database & SQL Soon 🌐Web Development Soon ☁️Cloud & DevOps Soon 🤖AI & ML Soon 📄Resume Prep Soon 🎤Interview Prep Soon 💼Freelancing Soon 🚀SaaS & Side Projects Soon 🤖Automation Soon
Beginner 🕑 11 min read 👁 2 views 📅 Oct 21, 2026

Debugging: Finding and Fixing Bugs with the Console and DevTools

Learn to read JavaScript error messages, inspect values with console.log, typeof and console.table, and pause code with breakpoints in Chrome DevTools to fix a broken shopping cart total.

When the Total Says Rs. 10050

Rohan is building an online cart for his uncle’s stationery shop in Jaipur. A customer buys a pack of notebooks for Rs. 100, delivery costs Rs. 50, and the page proudly shows: Total: Rs. 10050. No error appears. The code runs. It is simply wrong.

Every programmer, from a first-year student to a senior engineer, writes code with mistakes. These mistakes are called bugs, and finding and fixing them is called debugging. Good developers are not people who never make bugs. They are people who know how to find them quickly and calmly.

Here is Rohan’s page. Run it and look at the total:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Gupta Stationery Cart</title>
</head>
<body>
  <h2>Your Cart</h2>
  <p>Notebooks (pack of 5): Rs. <span id="subtotal">100</span></p>
  <p>Delivery: Rs. 50</p>
  <p><strong>Total: Rs. <span id="total"></span></strong></p>

  <script>
    const DELIVERY = 50;
    const subtotal = document.querySelector("#subtotal").textContent;
    const total = subtotal + DELIVERY;
    document.querySelector("#total").textContent = total;   // shows 10050!
  </script>
</body>
</html>

In this lesson you will learn to read error messages, use the console like a detective, and pause your code in Chrome DevTools to see what is really happening. By the end, you will fix Rohan’s cart and follow a checklist that works for almost any bug.

Reading Error Messages

When JavaScript cannot run a line, it stops and prints an error message in the console. Beginners often feel scared of red text, but an error message is a gift: it tells you what went wrong and where. Every message has three parts: the type of error, a short description, and the file and line number.

Error typeWhat it meansCommon cause
ReferenceErrorYou used a name JavaScript does not knowA typo in a variable name, or a variable used outside its scope
TypeErrorYou used a value in a way its type does not allowReading a property of undefined or null, or calling something that is not a function
SyntaxErrorThe code is not valid JavaScriptA missing bracket, quote or comma

ReferenceError: an unknown name

The example below has a typo on purpose. Notice that the lines before the error run normally, and everything after it never runs.

const cartTotal = 150;
console.log("Before the error");  // Before the error
console.log(cartTotl);  // ERROR: ReferenceError, cartTotl is not defined (a typo)
console.log("This line never runs");

TypeError: the wrong kind of value

The cart has no coupon, so cart.coupon is undefined. Asking undefined for .code is like asking an empty envelope for the letter inside.

const cart = { items: ["Notebook", "Pen"] };
console.log(cart.items.length);   // 2
console.log(cart.coupon);         // undefined (no coupon property)
console.log(cart.coupon.code);    // ERROR: TypeError, cannot read properties of undefined (reading 'code')

SyntaxError: the code cannot even start

A syntax error is different. The browser checks the grammar of the whole script before running it, so not a single line runs, not even the ones before the mistake. Here the closing ] is missing. Different browsers word the message differently, but both point to the same line:

const items = ["Notebook", "Pen";
// SyntaxError: missing ] after element list (Firefox)
// SyntaxError: Unexpected token ';' (Chrome)
Read the error message slowly, from left to right, then click the file name and line number on the right side of the console message. The browser jumps straight to the line with the problem.

console.log with Labels, and typeof

The most common debugging tool is still console.log. Rohan’s bug does not throw an error, so he needs to look inside his variables. Two habits make this far more useful:

  • Always add a label, such as console.log("subtotal:", subtotal). When you have ten logs, you will know which is which.
  • Check the type with typeof. Many bugs come from a value that looks right but has the wrong type.
// The same values as in the cart page
const subtotal = "100";   // text read from the page
const DELIVERY = 50;

// Unlabelled logs are hard to read
console.log(subtotal, DELIVERY);           // 100 50

// Labels tell you what each value is
console.log("subtotal:", subtotal);        // subtotal: 100
console.log("DELIVERY:", DELIVERY);        // DELIVERY: 50

// typeof shows the real problem
console.log("type of subtotal:", typeof subtotal);  // type of subtotal: string
console.log("type of DELIVERY:", typeof DELIVERY);  // type of DELIVERY: number

// Template literal logs are useful too
console.log(`total = ${subtotal + DELIVERY}`);          // total = 10050
console.log(`fixed = ${Number(subtotal) + DELIVERY}`);  // fixed = 150

There is the bug: subtotal is the string "100", because textContent always returns text. When + sees a string, it joins instead of adding, so "100" + 50 becomes "10050".

console.table, console.warn and console.error

The console has more tools than log. console.table shows a list of objects as a table, which is perfect for a cart. console.warn and console.error print messages in yellow and red, so important problems stand out.

const cart = [
  { item: "Notebook", price: 100, qty: 2 },
  { item: "Gel pen", price: 15, qty: 5 },
  { item: "Geometry box", price: "120", qty: 1 }
];

// See every item as a neat table with rows and columns
console.table(cart);

// Warnings and errors stand out in yellow and red
console.warn("Stock is low for Geometry box");
console.error("Price of Geometry box is text, not a number:", cart[2].price);
The Try it yourself console shows log, warn and error messages. A console.table appears in the browser’s own console instead: press F12 and open the Console tab to see it. In your own pages from VS Code, everything appears there.

Can you spot the hidden problem in the table? The price of the geometry box is "120" in quotes, a string, while the others are numbers. A table makes such differences easy to see.

Opening Chrome DevTools

Every modern browser has built-in developer tools (DevTools). They work on your own pages, the ones you open from VS Code, not inside the Try it yourself playground. You need a laptop or desktop for this part; phone browsers do not have them.

  1. Open your page in Chrome.
  2. Press F12, or Ctrl + Shift + I on Windows (Cmd + Option + I on a Mac). You can also right-click the page and choose Inspect.
  3. Click the Console tab. You see your logs and errors here, and you can type JavaScript directly, such as typeof subtotal, and press Enter.

The Sources Panel and Breakpoints

A log shows a value at one moment. A breakpoint pauses the whole program at a line, so you can look at every variable calmly, like pausing a cricket replay to see if the batter was out.

  1. In DevTools, open the Sources panel.
  2. On the left, click your file (for example index.html or script.js).
  3. Click a line number, such as the line const total = subtotal + DELIVERY;. A blue marker appears. This is your breakpoint.
  4. Refresh the page with F5. The code stops at that line, before running it.
  5. Move your mouse over subtotal to see its value, or look at the Scope section on the right, which lists every variable. You will see subtotal: "100" with quotes, which shows it is a string.
  6. Press F10 (Step over) to run one line at a time, and F8 (Resume) to continue normally. Click the blue marker again to remove the breakpoint.

The debugger statement

You can also put a breakpoint inside your code by writing the word debugger. When DevTools is open, the browser pauses on that line. When DevTools is closed, the line does nothing, so the example below runs normally in the playground. Copy it into your own file and open DevTools to see it pause on every loop.

const prices = [100, 15, 120];
let total = 0;

for (const price of prices) {
  debugger;   // with DevTools open, the browser pauses here on every loop
  total = total + price;
}

console.log("total:", total);  // total: 235

Remember to delete every debugger line before you share your website.

Real-Life Example: Fixing Rohan’s Cart

Using labelled logs and typeof, Rohan confirms that the subtotal is text. He converts it with Number(), adds a safety check with Number.isNaN, and the total becomes correct:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Gupta Stationery Cart</title>
</head>
<body>
  <h2>Your Cart</h2>
  <p>Notebooks (pack of 5): Rs. <span id="subtotal">100</span></p>
  <p>Delivery: Rs. 50</p>
  <p><strong>Total: Rs. <span id="total"></span></strong></p>

  <script>
    const DELIVERY = 50;
    const subtotalText = document.querySelector("#subtotal").textContent;
    console.log("subtotalText:", subtotalText, typeof subtotalText);  // subtotalText: 100 string

    const subtotal = Number(subtotalText);
    console.log("subtotal:", subtotal, typeof subtotal);  // subtotal: 100 number

    if (Number.isNaN(subtotal)) {
      console.error("Could not read the subtotal:", subtotalText);
    }

    const total = subtotal + DELIVERY;
    console.log("total:", total);  // total: 150
    document.querySelector("#total").textContent = total;
  </script>
</body>
</html>

Try these changes:

  1. Change the subtotal in the HTML to 1OO (with capital letter O, not zeros). Run it and read the red error message.
  2. Add a console.table of an array with the subtotal, delivery and total.
  3. Save the page on your computer, open it in Chrome and set a breakpoint on the const total line.

A Step-by-Step Debugging Checklist

  1. Reproduce the bug. Find the exact steps that make it happen every time.
  2. Read the console. Is there an error? Note its type, its message and its line number.
  3. Say what you expected. “I expected 150 but got 10050.” This often points to the cause.
  4. Look inside. Add labelled console.log lines and typeof checks, or set a breakpoint, just before the wrong result.
  5. Find the first wrong value. Work backwards until you find the line where a value first becomes wrong.
  6. Change one thing at a time, run again, and check the result.
  7. Clean up. Remove extra logs and debugger lines when the bug is fixed.

Common Mistakes

  • Ignoring the red text. Read the error type and line number before changing anything.
  • Fixing the line where the error appears, when the cause is earlier. In the TypeError example, the real problem is that coupon was never set. Look at where the value came from.
  • Logging without labels. A console full of bare numbers is confusing. Always add a label.
  • Changing many things at once. If it starts working, you will not know which change fixed it, and you may add new bugs.
  • Trusting that a value “looks like” a number. Text from the page, forms and URLs is always a string. Check with typeof.

Practice Task: Fix the Marks Calculator

Rohan’s cousin wrote a marks calculator, and it has three bugs. Run it, read the console, and use labelled logs and typeof to find each bug. When everything is fixed:

  • The total should be 405
  • The average should be 81
  • The result line should print Distinction without any error
// Rohan's marks calculator has 3 bugs. Find and fix them.
// Expected output:
// Total: 405
// Average: 81
// Result: Distinction

const marks = [78, "92", 85, 64, 86];   // one mark came from a text box
let total = 0;

for (let i = 0; i <= marks.length; i++) {
  total = total + marks[i];
}

const average = total / marks.length;
console.log("Total: " + total);
console.log("Average: " + average);

if (average > 80) {
  console.log("Result: " + reslt);
}
Show one possible answer (try it yourself first!)
const marks = [78, "92", 85, 64, 86];
let total = 0;

// Bug 1: the loop used <=, so it read marks[5], which is undefined.
// Bug 2: "92" is text, so + joined strings. Number() converts it.
for (let i = 0; i < marks.length; i++) {
  console.log("i:", i, "mark:", marks[i], typeof marks[i]);
  total = total + Number(marks[i]);
}

const average = total / marks.length;
console.log("Total: " + total);      // Total: 405
console.log("Average: " + average);  // Average: 81

// Bug 3: reslt was a typo (ReferenceError). Store the result first.
if (average > 80) {
  const result = "Distinction";
  console.log("Result: " + result);  // Result: Distinction
}

Key Takeaways

  • Error messages tell you the type, the reason and the line: ReferenceError (unknown name), TypeError (wrong kind of value), SyntaxError (invalid code).
  • Use console.log with labels and typeof to look inside your variables.
  • console.table, console.warn and console.error make data and problems easier to see.
  • Open DevTools with F12, set breakpoints in the Sources panel, and step through code with F10. The debugger statement does the same from your code.
  • Follow the checklist: reproduce, read, expect, look inside, find the first wrong value, change one thing, clean up.

❓ Frequently Asked Questions

When one side of + is a string, JavaScript joins the values as text instead of adding them. Convert the string first with Number("100").
Mobile browsers do not include full DevTools. Use a laptop or desktop for breakpoints and the Sources panel; in the playground you can still use console.log.
Yes, remove the logs you added for debugging, and always remove debugger statements. Keep only messages that help real users or other developers.
It means a variable or property has no value yet. Look at the line that should have given it a value; the real mistake is usually there.
Was this lesson helpful?

🎯 Finished this lesson?

🔗 Related Tutorials
🤖 Got a Doubt? Ask AI
Get instant answers in Hindi or English
🤖
Z2T Bot
Online
Ask me anything about this tutorial — I'm here! 👋