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
debuggerstatement - 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
- Reproduce it. Find the exact steps that make the bug happen every time.
- Describe it exactly. "Expected total 4995, got 49954995" is useful. "It's broken" is not.
- Find where it starts. Check the value at different points until you find the first place it is wrong.
- Understand the cause before changing anything.
- Fix it, changing one thing at a time.
- 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:
- Open dev tools and click the Sources tab.
- Open your JavaScript file.
- Click the line number where you want to pause. A blue marker appears.
- Do the action that runs the code (reload, click a button).
- 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:
| Button | Shortcut | What it does |
|---|---|---|
| Resume | F8 | Continue until the next breakpoint |
| Step over | F10 | Run the current line and go to the next |
| Step into | F11 | Go inside the function called on this line |
| Step out | Shift + F11 | Finish 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
| Bug | Example | How to spot it |
|---|---|---|
| Wrong type | "5" + 2 gives "52" | Log typeof |
| Off-by-one | Loop runs one time too many | Trace the loop by hand |
| Missing return | Function result is undefined | Check the function has return |
| Assignment in a condition | if (x = 5) | Look for single = in conditions |
| Undefined property | user.address.city crashes | Log the object one level at a time |
| Mutation | Changing a "copy" also changes the original | Check whether you really copied |
| Wrong order | Code uses a value before it is set | Step through with breakpoints |
| Async timing | Data used before it has arrived | Covered 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:
- Stay calm and say what you see: "The output is 103 instead of 13."
- Form a guess out loud: "I think quantity is a string."
- Check it: add a
console.logor trace by hand. - 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
debuggerand manyconsole.loglines 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
| Word | Meaning |
|---|---|
| Bug | A mistake that causes wrong behaviour |
| Reproduce | Make a bug happen again on purpose |
| Breakpoint | A point where the code pauses so you can inspect it |
| debugger | A statement that pauses code when dev tools are open |
| Step over / into / out | Ways to move through paused code |
| Call stack | The list of functions that led to the current line |
| Rubber duck debugging | Explaining code out loud to find mistakes |
| Linter | A 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.