Skip to the content

Lesson 44 of 296

Debugging your code

What you will learn

  • A calm, step-by-step way to find bugs
  • Using console methods well
  • Breakpoints and the debugger statement
  • Stepping through code in dev tools
  • Rubber duck debugging
  • The most common kinds of bugs
  • How to debug out loud in an interview
On this page

What is debugging?

A bug is a mistake in code that causes wrong behaviour. Debugging is the process of finding and fixing it. Lesson 6 covered reading error messages. This lesson covers bugs where the result is wrong but there may be no error at all.

The debugging process

  1. Reproduce it. Find the exact steps that make the bug happen every time.
  2. Describe it exactly. "Expected total 4995, got 49954995" is useful. "It's broken" is not.
  3. Find where it starts. Check the value at different points until you find the first place it is wrong.
  4. Understand the cause before changing anything.
  5. Fix it, changing one thing at a time.
  6. Test the fix, and check you did not break anything else.

Better console.log

Label your values:

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

Log several values in one object (shows their names automatically):

console.log({ price, quantity, total });

Shows { price: 10, quantity: "3", total: "103" }, which makes the bug obvious: quantity is a string.

Check the type:

console.log(typeof quantity);

Show arrays of objects as a table:

console.table(products);

Breakpoints

A breakpoint pauses your code at a chosen line, so you can see every variable's value at that moment, without adding any console.log.

In Chrome:

  1. Open dev tools and click the Sources tab.
  2. Open your JavaScript file.
  3. Click the line number where you want to pause. A blue marker appears.
  4. Do the action that runs the code (reload, click a button).
  5. The code pauses at that line.

Or write debugger in your code:

function calculateTotal(items) {
  debugger;
  let total = 0;
  ...
}

When dev tools are open, the code pauses there. Remove it when you are finished.

Stepping through code

When paused, use the buttons in the Sources tab:

ButtonShortcutWhat it does
ResumeF8Continue until the next breakpoint
Step overF10Run the current line and go to the next
Step intoF11Go inside the function called on this line
Step outShift + F11Finish the current function and return to the caller

While paused:

  • Scope panel: shows the value of every variable right now.
  • Watch panel: add expressions you want to keep an eye on, such as total * 2.
  • Call stack panel: shows which functions called which to get here.
  • Hover over a variable in the code to see its value.

Node.js code can be debugged the same way. VS Code has a built-in debugger with the same buttons.

Rubber duck debugging

Explain your code, line by line, out loud, to someone, or even to an object on your desk (traditionally a rubber duck). Very often you hear your own mistake while explaining. This works surprisingly well, and it is exactly the "think aloud" skill interviewers want.

Shrink the problem

If a big function is wrong:

  • Comment out half the code and see if the bug remains.
  • Test the function with the smallest, simplest input.
  • Copy the code into a fresh file with fake data, away from the rest of the app.

The most common bug types

BugExampleHow to spot it
Wrong type"5" + 2 gives "52"Log typeof
Off-by-oneLoop runs one time too manyTrace the loop by hand
Missing returnFunction result is undefinedCheck the function has return
Assignment in a conditionif (x = 5)Look for single = in conditions
Undefined propertyuser.address.city crashesLog the object one level at a time
MutationChanging a "copy" also changes the originalCheck whether you really copied
Wrong orderCode uses a value before it is setStep through with breakpoints
Async timingData used before it has arrivedCovered in Part 5

Preventing bugs

  • Small functions with one job are easier to check.
  • Clear names show mistakes faster.
  • Test edge cases: empty arrays, zero, negative numbers, missing values, very long text.
  • Linters such as ESLint warn about likely bugs while you type.
  • TypeScript (Part 9) catches type mistakes before the code runs.
  • Automated tests (Parts 11, 14 and 21) catch bugs before users do.

Debugging in an interview

When your code fails in a live interview:

  1. Stay calm and say what you see: "The output is 103 instead of 13."
  2. Form a guess out loud: "I think quantity is a string."
  3. Check it: add a console.log or trace by hand.
  4. Fix it and explain why it happened.

Interviewers judge how you debug as much as whether you fix it. Silence is the worst choice.

Common mistakes

  • Changing code randomly until it works.
  • Changing many things at once.
  • Not reading the actual values, and assuming instead.
  • Leaving debugger and many console.log lines in finished code.

How to say it in an interview

"I first reproduce the bug reliably, then narrow down where the value first goes wrong, using labelled console logs or breakpoints in dev tools so I can inspect variables and step through the code. I form a hypothesis, test it, and change one thing at a time. Afterwards I add a test or an edge-case check so the bug cannot come back."

Key words

WordMeaning
BugA mistake that causes wrong behaviour
ReproduceMake a bug happen again on purpose
BreakpointA point where the code pauses so you can inspect it
debuggerA statement that pauses code when dev tools are open
Step over / into / outWays to move through paused code
Call stackThe list of functions that led to the current line
Rubber duck debuggingExplaining code out loud to find mistakes
LinterA tool that warns about likely mistakes in code

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.