# Debugging

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Error Handling
Source: https://www.devtutorials.ai/learn/javascript/error-handling/debugging

> What debugging is and why it matters, console debugging with log, error, warn and table, breakpoints and stepping in DevTools, watching variables and inspecting scope, reading a stack trace, and fixing the most common beginner bugs.

## What Is Debugging?

**Bug** = a mistake in the code. **Debugging** = finding out why the program is wrong, and fixing it.

- Compare what you **expected** with what you **got**.
- Look at real values: print them, pause the code, read the error.
- Fix the **root cause**, not just the line that crashed.

**Simple lesson:** do not guess, look. Every bug leaves evidence.

### A Real-World Example

A customer buys 2 notebooks (₹240) and 4 pens (₹60), but the cart says ₹60.
Printing the total after each item shows it **dropped** from 240 to 60.
The line used `=` instead of `+=`. One character, found in a minute by looking.

<figure className="ts-fig">
  <svg viewBox="0 0 560 170" role="img" aria-label="A magnifying glass moves along three lines of code and stops on the line total = line, which turns red." width="100%">
    <rect x="0" y="0" width="560" height="170" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="40" y="30" width="480" height="30" rx="6" fill="#ffffff" stroke="#e2e8f0" />
    <text x="56" y="50" fontSize="13" fontFamily="monospace" fill="#334155">for (const item of cart) &#123;</text>
    <rect x="40" y="66" width="480" height="30" rx="6" fill="#fee2e2" stroke="#dc2626" />
    <text x="56" y="86" fontSize="13" fontFamily="monospace" fill="#991b1b">  total = item.price * item.quantity;</text>
    <rect x="40" y="102" width="480" height="30" rx="6" fill="#ffffff" stroke="#e2e8f0" />
    <text x="56" y="122" fontSize="13" fontFamily="monospace" fill="#334155">&#125;  // total: 240 → 60 ✗</text>
    <circle r="14" cy="81" fill="none" stroke="#2563eb" strokeWidth="4"><animate attributeName="cx" values="80;300;470;470" keyTimes="0;0.4;0.7;1" dur="3s" repeatCount="indefinite" /></circle>
    <text x="280" y="155" textAnchor="middle" fontSize="12" fill="#475569">Print the values; the line where they go wrong is the bug.</text>
  </svg>
  <figcaption>Follow the values until they stop matching what you expected.</figcaption>
</figure>

Some boxes are broken on purpose, and each is followed by its fix. Breakpoints work in the browser's DevTools, so those parts show the steps and a runnable stand-in.

## What You Will Learn

1. What debugging is, and why looking beats guessing.
2. `console.log()`, `console.error()`, `console.warn()` and `console.table()`.
3. Breakpoints, `debugger;` and stepping through code.
4. Watching variables and reading scopes.
5. Reading stack traces, and fixing the four most common bugs.

## Introduction to Debugging

### What is Debugging?

Expected ₹300, got ₹60. The gap tells you where to look: `total` is **replaced** on every pass instead of added to.

```js runnable title="A cart total that looks right but is wrong"
const cart = [
  { name: "Notebook", price: 120, quantity: 2 },
  { name: "Pen", price: 15, quantity: 4 },
];

let total = 0;
for (const item of cart) {
  total = item.price * item.quantity;
}

console.log("Cart total:", total);
```

Expected output:

```text
Cart total: 60
```

### Why Debugging is Important

- A program that runs is not always right. The cart above gave no error.
- Random changes take hours. Looking at values step by step takes minutes.

Do not guess, look. Print the values, pause the code, or read the error.

## Console Debugging

### `console.log()`

Print values with a **label**, so each number is easy to identify. The total goes **down** after the pens, so that line is wrong.

```js runnable title="Printing the running total on every pass shows where it goes wrong"
const cart = [
  { name: "Notebook", price: 120, quantity: 2 },
  { name: "Pen", price: 15, quantity: 4 },
];

let total = 0;
for (const item of cart) {
  total = item.price * item.quantity;
  console.log(`after ${item.name}, total is`, total);
}
```

Expected output:

```text
after Notebook, total is 240
after Pen, total is 60
```

### `console.error()`

Marks a message as an error (red in browsers; `[error]` here). It only **reports**; the code keeps running.

```js runnable title="Reporting a problem as an error message"
const payment = { orderId: 5012, amount: 0 };

if (payment.amount <= 0) {
  console.error(`Order ${payment.orderId} has an invalid amount:`, payment.amount);
}

console.log("Checkout finished.");
```

Expected output:

```text
[error] Order 5012 has an invalid amount: 0
Checkout finished.
```

### `console.warn()`

Marks a warning (yellow; `[warn]` here): not broken yet, but worth attention.

```js runnable title="A warning for stock that is running low"
const stock = { name: "Stapler", quantity: 2 };

if (stock.quantity < 5) {
  console.warn(`Only ${stock.quantity} ${stock.name}s left in stock`);
}

console.log("Stock check complete.");
```

Expected output:

```text
[warn] Only 2 Staplers left in stock
Stock check complete.
```

### `console.table()`

Shows an array of objects as a table, one row per object. The boxes here print plain text, so this is the browser's output:

```js
const orders = [
  { id: 101, customer: "Asha", total: 250 },
  { id: 102, customer: "Ravi", total: 180 },
  { id: 103, customer: "Meera", total: 420 },
];

console.table(orders);
```

```text
┌─────────┬─────┬──────────┬───────┐
│ (index) │ id  │ customer │ total │
├─────────┼─────┼──────────┼───────┤
│ 0       │ 101 │ 'Asha'   │ 250   │
│ 1       │ 102 │ 'Ravi'   │ 180   │
│ 2       │ 103 │ 'Meera'  │ 420   │
└─────────┴─────┴──────────┴───────┘
```

Remove debugging logs after the fix. If a check is still useful, turn it into a real guard that throws.

## Breakpoints

### Setting Breakpoints

**Breakpoint** = a marker that pauses the code right before a line runs, so you can see every value.

Open it (Chrome or Edge; Firefox is similar):

1. Open DevTools: **F12**, **Ctrl+Shift+I** (Windows) or **Cmd+Option+I** (Mac).
2. Select **Sources** (Firefox: **Debugger**).
3. Open your script from the file list on the left.

Then pause:

1. Click a line number. A blue marker appears.
2. Do whatever runs that code, like reloading or clicking.
3. The line is highlighted, and the right panels show the current values.

You can also write `debugger;` in the code. It pauses there only while DevTools is open:

```js
function applyDiscount(price, percent) {
  debugger; // the browser pauses here when DevTools is open
  const discount = price * (percent / 100);
  return price - discount;
}

applyDiscount(500, 10);
```

Remove `debugger;` before sharing code. The boxes here cannot pause, but a log in the same place shows the same values:

```js runnable title="What a breakpoint on the discount line would show you"
function applyDiscount(price, percent) {
  console.log("paused here with", { price, percent });
  const discount = price * (percent / 100);
  return price - discount;
}

console.log("Final price:", applyDiscount(500, 10));
```

Expected output:

```text
paused here with {
  "price": 500,
  "percent": 10
}
Final price: 450
```

### Stepping Through Code

**Stepping** = running paused code one line at a time:

1. **Resume** (**F8**): run to the next breakpoint.
2. **Step over** (**F10**): run this line, including any call on it, and pause on the next.
3. **Step into** (**F11**): go inside the function called on this line.
4. **Step out** (**Shift+F11**): finish this function and pause back in the caller.

This prints the lines in the order **Step into** would visit them:

```js runnable title="The order in which stepping would visit each line"
function priceWithTax(price) {
  console.log("step into priceWithTax, price =", price);
  const tax = price * 0.18;
  console.log("tax worked out as", tax);
  return price + tax;
}

console.log("start");
const final = priceWithTax(200);
console.log("step out, final =", final);
```

Expected output:

```text
start
step into priceWithTax, price = 200
tax worked out as 36
step out, final = 236
```

## Inspecting Variables

### Watching Variable Values

A **watch expression** is re-checked every time the code pauses:

1. Pause at a breakpoint.
2. Open the **Watch** section on the right.
3. Click **+** and type, for example, `total`.
4. Press **Step over** repeatedly and watch the value change.

The runnable version is a labelled log inside the loop:

```js runnable title="Watching total and the line value on every pass of the loop"
const cart = [
  { name: "Notebook", price: 120, quantity: 2 },
  { name: "Pen", price: 15, quantity: 4 },
  { name: "Stapler", price: 90, quantity: 1 },
];

let total = 0;
for (const item of cart) {
  const lineTotal = item.price * item.quantity;
  total += lineTotal;
  console.log(`watch: lineTotal = ${lineTotal}, total = ${total}`);
}
```

Expected output:

```text
watch: lineTotal = 240, total = 240
watch: lineTotal = 60, total = 300
watch: lineTotal = 90, total = 390
```

### Scope Inspection

**Scope** = the variables a line can see. The **Scope** panel groups them:

- **Local:** the paused function's variables and parameters.
- **Closure:** variables from an outer function it can still reach.
- **Script:** top-level `let` and `const`.
- **Global:** browser built-ins like `console` and `Math`.

```js runnable title="The variables each scope group would show for the inner line"
const storeName = "Asha's Books";

function makeReceipt(customer) {
  const discount = 10;

  function line(item) {
    console.log("Local:  ", { item });
    console.log("Closure:", { customer, discount });
    console.log("Script: ", { storeName });
    return `${customer} bought ${item} at ${storeName}`;
  }

  return line("Atlas");
}

console.log(makeReceipt("Ravi"));
```

Expected output:

```text
Local:   {
  "item": "Atlas"
}
Closure: {
  "customer": "Ravi",
  "discount": 10
}
Script:  {
  "storeName": "Asha's Books"
}
Ravi bought Atlas at Asha's Books
```

The boxes here run your code inside a function, so their top-level variables act like the **Script** group.

## Stack Trace

### What is a Stack Trace?

**Stack trace** = the list of function calls in progress when an error happened. A hand-written example:

```text
TypeError: Cannot read properties of undefined (reading 'toFixed')
    at formatPrice (shop.js:2:22)
    at showProduct (shop.js:7:26)
    at renderPage (shop.js:12:3)
    at shop.js:15:1
```

- Line 1: **what** went wrong.
- Line 2: **where**: `formatPrice`, file `shop.js`, line 2, column 22.
- Lines below: **who called it**, down to the start.

**Why "stack"?** Each call sits on top of its caller, like a stack of plates.

### Function Call Chain

Calls build up outer to inner. A stack trace lists them in **reverse**: innermost at the top.

```js runnable title="Logging each call as it starts shows the chain in the order it builds"
function formatPrice(price) {
  console.log("  3. formatPrice starts, price =", price);
  return "₹" + price.toFixed(2);
}

function showProduct(product) {
  console.log(" 2. showProduct starts with", product.name);
  return `${product.name}: ${formatPrice(product.price)}`;
}

function renderPage() {
  console.log("1. renderPage starts");
  return showProduct({ name: "Notebook", price: 120 });
}

console.log(renderPage());
```

Expected output:

```text
1. renderPage starts
 2. showProduct starts with Notebook
  3. formatPrice starts, price = 120
Notebook: ₹120.00
```

### Finding the Root Cause of an Error

The error is thrown inside `formatPrice`, but `formatPrice` is fine. It received `undefined`.

```js runnable expect-error title="formatPrice throws, but the mistake is somewhere else"
function loadProduct() {
  return { name: "Notebook", cost: 120 };
}

function formatPrice(price) {
  return "₹" + price.toFixed(2);
}

function showProduct() {
  const product = loadProduct();
  return `${product.name}: ${formatPrice(product.price)}`;
}

console.log(showProduct());
```

Print the value passed down the chain. The product has `cost`, not `price`, so fix `showProduct`:

```js runnable title="Printing the value passed down the chain reveals the real cause"
function loadProduct() {
  return { name: "Notebook", cost: 120 };
}

const product = loadProduct();
console.log("product is", product);
console.log("product.price is", product.price);
```

Expected output:

```text
product is {
  "name": "Notebook",
  "cost": 120
}
product.price is undefined
```

The top of a stack trace shows where the problem was **noticed**. Follow the chain down to where the wrong value was **made**.

## Debugging Common Issues

### Undefined Values

A function with no `return` gives `undefined`, and `500 - undefined` is `NaN`.

```js runnable title="Broken: getDiscount forgets to return, so the total becomes NaN"
function getDiscount(price) {
  price * 0.1;
}

const price = 500;
const discount = getDiscount(price);

console.log("discount:", discount);
console.log("total:", price - discount);
```

Expected output:

```text
discount: undefined
total: NaN
```

```js runnable title="Fixed: return the value the function works out"
function getDiscount(price) {
  return price * 0.1;
}

const price = 500;
const discount = getDiscount(price);

console.log("discount:", discount);
console.log("total:", price - discount);
```

Expected output:

```text
discount: 50
total: 450
```

Print values one step earlier. Where `undefined` first appears is usually the bug.

### Null Reference Errors

A search found nothing and returned `null`; reading `.name` from it throws.

```js runnable expect-error title="Broken: findCustomer returns null, and the code reads .name from it"
const customerList = [
  { id: 1, name: "Asha" },
  { id: 2, name: "Ravi" },
];

function findCustomer(id) {
  return customerList.find((customer) => customer.id === id) ?? null;
}

console.log("Hello,", findCustomer(2).name);
console.log("Hello,", findCustomer(7).name);
```

Use `?.` to stop at `null`, and `??` for a default:

```js runnable title="Fixed: check for null before reading from it"
const customerList = [
  { id: 1, name: "Asha" },
  { id: 2, name: "Ravi" },
];

function findCustomer(id) {
  return customerList.find((customer) => customer.id === id) ?? null;
}

for (const id of [2, 7]) {
  const customer = findCustomer(id);
  const name = customer?.name ?? "Guest";
  console.log("Hello,", name);
}
```

Expected output:

```text
Hello, Ravi
Hello, Guest
```

### Type Errors

The price came from a form as the text `"120"`, and strings have no `toFixed`.

```js runnable expect-error title="Broken: the price arrived as a string, and strings have no toFixed"
const formInput = { product: "Notebook", price: "120" };

console.log("Formatting the price...");
console.log("Price: ₹" + formInput.price.toFixed(2));
```

Check with `typeof`, then convert with `Number()`:

```js runnable title="Fixed: check the type, then convert the text to a number"
const formInput = { product: "Notebook", price: "120" };

console.log("type of price:", typeof formInput.price);

const price = Number(formInput.price);
console.log("Price: ₹" + price.toFixed(2));
```

Expected output:

```text
type of price: string
Price: ₹120.00
```

### Incorrect Function Calls

Names are case-sensitive: `foreach` is not `forEach`.

```js runnable expect-error title="Broken: forEach is spelled with a lower-case e"
const items = ["Pen", "Notebook", "Stapler"];

items.foreach((item) => console.log(item));
```

Arguments in the wrong order run without error, but give a wrong answer:

```js runnable title="Fixed: the right spelling, and arguments in the order the function expects"
const items = ["Pen", "Notebook", "Stapler"];
items.forEach((item) => console.log(item));

function applyDiscount(price, percent) {
  return price - price * (percent / 100);
}

console.log("wrong order:", applyDiscount(10, 500));
console.log("right order:", applyDiscount(500, 10));
```

Expected output:

```text
Pen
Notebook
Stapler
wrong order: -40
right order: 450
```

## Debugging on a Web Page

This cart shows a wrong total. Read the labelled logs in the Console to find the line where the values go wrong.

```js runnable preview="cart" title="Find the bug with labelled logs"
const items = [
  { name: "Notebook", price: 60, qty: 2 },
  { name: "Steel bottle", price: "299", qty: 1 },
];
const list = document.querySelector("#cart");
let total = 0;

for (const item of items) {
  const line = item.qty === 1 ? item.price : item.price * item.qty;
  console.log(`line for ${item.name}:`, line, "| type:", typeof line);
  total = total + line;
  console.log("total so far:", total, "| type:", typeof total);
  const li = document.createElement("li");
  li.textContent = `${item.name} × ${item.qty}`;
  list.append(li);
}
document.querySelector("#total").textContent = `₹${total}`;
```

The page shows ₹120299. The logs show the bottle's line is a `string`, so `+` joined text. Fix it with `Number(item.price)`, and the total becomes ₹419.

**Easy way to remember:** **Expect → Print → Compare → Fix the cause.**

## TL;DR

- Start with "what did I expect, and what did I get?"
- Log with labels; `console.error`/`warn` only report.
- Breakpoints and `debugger;` pause code; step over, into and out.
- Read a stack trace top-down; fix where the bad value was made.
- `undefined` → missing `return` or key; `null` → use `?.`; `is not a function` → wrong type or spelling.

## Try this

In the **Null Reference Errors** fix, change `"Guest"` to `"Unknown customer"` and loop over `[2, 7, 1]`. Customers 2 and 1 print their names; 7 gets your new default.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Guessing at `NaN` | It is somewhere in the maths | Print each value one step earlier | You miss the `undefined` source |
| Reading `.name` from a search result | Searches always find | They can return `null` | `Cannot read properties of null` |
| Calling `toFixed` on form input | Inputs are numbers | They are strings; use `Number()` | `toFixed is not a function` |
| `items.foreach(...)` | Case does not matter | Names are case-sensitive | `foreach is not a function` |
| Fixing the top line of the trace | The crash line is the bug | The cause is often lower down | The bug comes back |
| Relying on `console.error` to stop | It halts the code | It only reports | The program carries on wrongly |

## Quick reference

<div className="tscroll">

| Syntax or tool | Meaning |
|---|---|
| `console.log(label, value)` | print a labelled value |
| `console.error(message)` | print a message marked as an error, without stopping |
| `console.warn(message)` | print a message marked as a warning |
| `console.table(array)` | draw an array of objects as a table, in browser DevTools |
| `debugger;` | pause at this line while DevTools is open |
| click a line number in **Sources** | set a breakpoint on that line |
| **F8** / **F10** / **F11** / **Shift+F11** | resume, step over, step into, step out |
| **Watch** panel | re-check an expression every time the code pauses |
| **Scope** panel | list the Local, Closure, Script and Global variables |
| top line of a stack trace | the error and where it was thrown |
| `typeof value` | check what type a value really is |
| `value?.property ?? fallback` | read a property safely, with a default |

</div>

## Exercises

## What to Remember

- Do not guess, look.
- Logs, breakpoints and stack traces are your evidence.
- Fix the place where the wrong value was made.

Next: **Asynchronous Fundamentals**. Code that finishes later, like timers and callbacks, and the event loop that decides what runs when.
