Debugging Basics

Finding and fixing bugs: reading errors and stack traces, printing, breakpoints and minimal reproductions.

What is it?

Debugging is finding out why a program doesn't do what you expected, then fixing it. Every programmer spends a lot of time on it, and it's a skill you can learn, not luck.

The core loop:

1. Reproduce the bug reliably. If you can't trigger it on demand, you can't tell whether you've fixed it. 2. Read the error message and stack trace carefully. They usually name the error type, the message, and the exact file and line. 3. Form a hypothesis: "I think total is a string here, not a number." 4. Test it with print statements, a debugger or a small experiment. 5. Fix the cause, not just the symptom, then confirm the bug is gone and nothing else broke.

Tools and techniques:

- Print debugging: print values at key points to see what's really happening. Simple and always available. - Debuggers: pause the program at a breakpoint, inspect every variable, and step through line by line. - Rubber-duck debugging: explain the code, line by line, out loud (to a rubber duck, or a colleague). Saying what each line should do often exposes where it doesn't. - Minimal reproduction: shrink the failing case to the smallest code and input that still shows the bug.

Explain like I'm 10

Debugging is detective work. The error message is the first clue, the stack trace is the trail of footprints, prints and breakpoints are interviews with witnesses, and a minimal reproduction is reconstructing the crime scene with nothing but the essentials.

Examples

Reading a Python traceback

def average(numbers):
    return sum(numbers) / len(numbers)

def report(scores):
    return "Average: " + average(scores)

print(report([80, 90, 70]))

# Traceback (most recent call last):
#   File "app.py", line 7, in <module>
#     print(report([80, 90, 70]))
#   File "app.py", line 5, in report
#     return "Average: " + average(scores)
# TypeError: can only concatenate str (not "float") to str

Read a Python traceback from the bottom up: the last line is the error type and message; the frame just above it is where it happened (line 5). The fix: "Average: " + str(average(scores)).

Print debugging and breakpoints in JavaScript

function applyDiscount(price, percent) {
  console.log({ price, percent });     // inspect inputs as a labelled object
  const discounted = price - price * percent;
  console.log("discounted:", discounted);
  return discounted;
}

applyDiscount(100, 20); // -1900?! percent should be 0.2, not 20

// Pause here in the browser DevTools or Node inspector:
function applyDiscountDebug(price, percent) {
  debugger; // execution stops on this line when DevTools is open
  return price - price * percent;
}

Logging inputs immediately showed the cause: the caller passed 20 instead of 0.2. The debugger statement (or clicking a line number in DevTools) pauses execution so you can inspect variables and step through.

Python's built-in debugger

def total_price(items):
    total = 0
    for item in items:
        breakpoint()   # pauses here and opens pdb
        total += item["price"] * item["qty"]
    return total

total_price([{"price": 5, "qty": 2}, {"price": 3, "qty": "4"}])

# At the (Pdb) prompt:
#   p item       print a variable
#   n            next line
#   s            step into a function call
#   c            continue to the next breakpoint
#   q            quit

breakpoint() drops you into pdb. On the second item you'd see qty is the string "4", explaining why the total is wrong (3 * "4" is "444", and adding that to an int raises a TypeError).

How it works

Stack traces are a snapshot of the call stack at the moment of the error: which function was running, which function called it, and so on.

- Python prints "most recent call last": read from the bottom up. - JavaScript prints the error first, then frames from the most recent call downward: read from the top.

Focus on frames from your code; frames inside libraries usually mean you passed something wrong into them.

Debuggers work with the language runtime to pause execution at chosen lines. While paused you can:

  • Step over: run the current line, including any calls, and stop at the next.
  • Step into: enter the function called on this line.
  • Step out: finish the current function and return to its caller.
  • Watch expressions and inspect the call stack.
  • Use conditional breakpoints that only pause when, say, i == 500.

Minimal reproductions work by elimination: remove code and data in chunks. If the bug remains, that part wasn't needed. What's left points at the cause. Bisecting history (git bisect) applies the same idea to commits.

┌───────────────┐
     │  Reproduce    │◄──────────────────────────┐
     └──────┬────────┘                           │
            ▼                                    │
     ┌───────────────┐   read error, trace,      │
     │  Observe      │   prints, debugger        │
     └──────┬────────┘                           │
            ▼                                    │
     ┌───────────────┐                           │
     │  Hypothesize  │                           │
     └──────┬────────┘                           │
            ▼                     wrong guess    │
     ┌───────────────┐ ──────────────────────────┘
     │  Test it      │
     └──────┬────────┘ confirmed
            ▼
     Fix cause → re-run → add a test so it stays fixed

Why does it exist?

Code is written by people, and people make mistakes. Requirements change, inputs are messier than expected, and code interacts in ways no one predicted. A systematic debugging approach turns hours of guessing into a short, repeatable process.

When to use it

- Read the error first, every time. It's the cheapest clue. - Print debugging for quick checks, code that runs once, or environments where a debugger is awkward (servers, CI logs). - A debugger when you need to see many variables, follow a complex path, or don't know where to put prints. - Rubber-ducking when you're stuck and "everything looks right". - A minimal reproduction before asking for help or filing a bug report; often you'll find the cause while making it.

When not to use it

- Don't change random things hoping the bug disappears ("shotgun debugging"); you might hide it rather than fix it. - Don't leave debug prints and debugger statements in committed code; use proper logging for things you want to keep. - Don't wrap failing code in a try that swallows the error to make it "go away"; the bug is still there, now hidden.

Common mistakes

  • Not reading the error message, or reading only the first line of a long trace instead of finding the frame in your own code.

  • Assuming you know what a variable contains instead of checking it.

  • Fixing the symptom (special-casing the bad value) instead of finding where the bad value came from.

  • Making several changes at once, so you can't tell which one fixed (or broke) things.

  • Not adding a test after fixing a bug, so it quietly comes back later.

Practice exercises

  1. Easy:

    Write a program that crashes with a KeyError (Python) or TypeError: Cannot read properties of undefined (JavaScript). Read the trace, identify the exact line and cause, and fix it.

  2. Medium:

    Write a function with an off-by-one bug that sums only the first n−1 items of a list. Find it twice: once with print statements and once by stepping through with a debugger. Compare the experiences.

  3. Hard:

    Take a buggy 50+ line program (or one you wrote earlier) and produce a minimal reproduction under 10 lines that still shows the bug. Write the bug report you'd file: steps, expected vs actual behavior, environment.

Interview questions

How do you approach a bug you've never seen before?

Reproduce it reliably, read the error and stack trace, narrow down where behavior diverges from expectations (prints, debugger, bisecting), form and test a hypothesis, fix the root cause, then add a test that would have caught it.

What is a stack trace?

A list of the active function calls at the point an error occurred, with file names and line numbers. It shows where the error happened and the chain of calls that led there.

In which order do you read a Python traceback versus a JavaScript stack trace?

Python lists the most recent call last, so the error and its location are at the bottom. JavaScript prints the error message first, followed by the most recent frame, so the relevant location is at the top.

What is a breakpoint?

A marker that pauses execution at a specific line so you can inspect variables, the call stack, and step through code. Conditional breakpoints pause only when an expression is true.

What's the difference between step over, step into and step out?

Step over runs the current line, including any function calls, and stops at the next line. Step into enters the function being called. Step out runs until the current function returns to its caller.

What is rubber-duck debugging and why does it work?

Explaining code line by line to someone, or something, that knows nothing about it. Saying what each line is supposed to do forces you to check assumptions you'd otherwise skim past.

What is a minimal reproducible example and why is it valuable?

The smallest code and input that still trigger the bug. It isolates the cause, makes the problem easy for others to understand and test, and the process of shrinking it often reveals the bug.

What is `git bisect`?

A Git command that binary-searches commit history to find the commit that introduced a bug. You mark a good and a bad commit, then test the commits Git checks out until it identifies the culprit.

Print debugging or a debugger: which is better?

Neither always. Prints are quick, work anywhere and leave a log of a whole run. Debuggers let you inspect everything at a moment and explore interactively without re-running. Good developers use both.

Scenario: a bug only happens in production, never locally. How do you investigate?

Gather evidence from production (logs, error reports with stack traces, the exact inputs). Look for differences: data, configuration, environment variables, versions, load and timing. Then reproduce with production-like data or config locally, and add logging where evidence is missing.