Basic JavaScript Debugging Tips for Beginners
Learn essential JavaScript debugging techniques including breakpoints, the debugger statement, watch expressions, and Chrome DevTools workflows. Move beyond console.log with practical, hands-on debugging strategies.
Every developer writes bugs. The difference between a frustrating 3-hour bug hunt and a 10-minute fix is not writing fewer bugs; it is knowing how to find them systematically. Most beginners rely exclusively on console.log() to debug JavaScript. While logging has its place, browser DevTools provide far more powerful tools: breakpoints that pause execution, a step-by-step debugger, watch expressions, the call stack viewer, and network inspection.
This tutorial teaches you the debugging techniques that professional developers use daily. You will learn how to pause code at specific lines, inspect variable values in real time, step through function calls, and identify the exact point where your logic goes wrong.
Using console.log() Effectively
Before diving into DevTools, let's cover how to use console methods strategically rather than scattering console.log() everywhere.
Log With Context, Not Just Values
The most common mistake is logging a value without identifying what it represents:
// Bad — what does "3" mean?
console.log(items.length);
// Good — instantly clear
console.log('Cart items count:', items.length);
// Better — includes the full object for inspection
console.log('Cart state:', { items, total, discount });Use Meaningful Labels When Logging Multiple Values
When debugging a function, log the input and output together:
function calculateDiscount(price, membershipLevel) {
console.log('calculateDiscount input:', { price, membershipLevel });
let discount = 0;
if (membershipLevel === 'gold') discount = price * 0.2;
if (membershipLevel === 'silver') discount = price * 0.1;
console.log('calculateDiscount output:', discount);
return discount;
}Use console.table() for Arrays and Objects
When debugging data structures, console.table() shows the data in a grid that is far easier to scan. If you have rows of data, use a table instead of logging each row:
const orders = [
{ id: 1, customer: 'Alice', total: 42.50, status: 'shipped' },
{ id: 2, customer: 'Bob', total: 0, status: 'pending' },
{ id: 3, customer: 'Charlie', total: 156.99, status: 'delivered' },
];
console.table(orders);
// Displays a sortable table — immediately spot that Bob's total is 0The debugger Statement
The debugger statement is a built-in JavaScript keyword that pauses execution at the exact line where it appears. When DevTools is open, hitting a debugger statement is like hitting a breakpoint you set in the source code:
function processUserInput(input) {
const trimmed = input.trim();
const normalized = trimmed.toLowerCase();
debugger; // Execution pauses here when DevTools is open
if (normalized.includes('admin')) {
return { role: 'admin', value: normalized };
}
return { role: 'user', value: normalized };
}When execution pauses at debugger:
- The DevTools Sources panel opens automatically
- You can hover over any variable to see its current value
- The Scope panel (right side) shows all local, closure, and global variables
- You can type expressions in the Console panel (they execute in the current scope)
Remove debugger Before Committing
The debugger statement pauses execution even in production if a user has DevTools open. Always remove debugger statements before pushing code. Use ESLint's no-debugger rule to catch missed ones.
When to Use debugger vs console.log()
| Scenario | Use | Why |
|---|---|---|
| Check a single variable value | console.log() | No need to pause execution |
| Inspect multiple variables in context | debugger | See all variables at once in the Scope panel |
| Step through branching logic | debugger | Walk through each condition manually |
| Check what a loop does on iteration 47 | debugger with conditional | Can't practically log 47 iterations |
| Quick check during development | console.log() | Faster than opening DevTools |
| Diagnose a complex state bug | debugger | Need to inspect closures and call stack |
Chrome DevTools: The Sources Panel
The Sources panel is your primary debugging interface. Here is how to open it and use its core features.
Opening DevTools
| Method | Shortcut |
|---|---|
| Open DevTools | F12 or Ctrl+Shift+I (Windows) / Cmd+Option+I (Mac) |
| Open directly to Sources | Ctrl+Shift+I then click "Sources" tab |
| Open Console drawer in Sources | Esc while in Sources panel |
Setting Breakpoints
Instead of adding debugger statements to your code, you can click on line numbers in the Sources panel to set breakpoints. This is better because:
- It does not require changing your source code
- You can enable/disable breakpoints without editing
- You can set conditional breakpoints
- Breakpoints persist across page reloads
To set a breakpoint:
- Open DevTools (F12)
- Go to the Sources panel
- Navigate to your JavaScript file in the left panel
- Click the line number where you want to pause
The line number turns blue, indicating an active breakpoint.
Conditional Breakpoints
Right-click a line number and select "Add conditional breakpoint." Enter a JavaScript expression. The breakpoint only triggers when the expression evaluates to true:
// You want to pause only when a specific user is processed
// Right-click line, add condition: user.id === 42
function processUser(user) {
const profile = loadProfile(user.id);
// Breakpoint with condition "user.id === 42" on this line
updateDashboard(profile);
}This is invaluable when debugging loops or event handlers that fire thousands of times. Instead of pausing on every iteration, you pause only on the case that matters.
Logpoints (Non-Breaking Log Statements)
Right-click a line number and select "Add logpoint." Enter a message template. The expression is logged to the console without pausing execution, and without modifying your code:
Logpoint expression: 'User:', user.name, 'Score:', user.score
This gives you console.log() behavior without touching your source files.
Stepping Through Code
Once execution is paused (via breakpoint, debugger, or error), you have four stepping controls:
| Button | Shortcut | Action |
|---|---|---|
| Resume | F8 | Continue running until the next breakpoint |
| Step Over | F10 | Execute the current line and move to the next line |
| Step Into | F11 | If the current line calls a function, go inside that function |
| Step Out | Shift+F11 | Finish the current function and pause at the caller |
Practical Stepping Example
Consider this code with a bug (the discount calculation is wrong):
function checkout(cart) {
let total = 0;
for (const item of cart.items) {
total += item.price * item.quantity;
}
const discount = applyDiscount(total, cart.couponCode);
const finalTotal = total + discount; // Bug: should be total - discount
return { total, discount, finalTotal };
}
function applyDiscount(total, code) {
if (code === 'SAVE20') return total * 0.2;
if (code === 'SAVE10') return total * 0.1;
return 0;
}Debugging workflow:
- Set a breakpoint on the line
const discount = applyDiscount(...); - Trigger the checkout function
- When paused, hover over
totalto verify it is correct - Press F11 (Step Into) to go inside
applyDiscount() - Step through the if statements with F10 (Step Over)
- Verify the returned discount value
- Press Shift+F11 (Step Out) to return to the checkout function
- Hover over
finalTotaland see it istotal + discountinstead oftotal - discount
Inspecting Variables and Scope
When execution is paused, the right panel in Sources shows three key sections:
Scope Panel
Displays all variables accessible at the current execution point:
- Local: variables declared in the current function
- Closure: variables from outer scopes that this function closes over
- Global: the global
windowobject (usually very large; rarely needed)
function createCounter(initialValue) {
let count = initialValue; // Visible in "Closure" scope when inside increment()
function increment(amount) {
// When paused here:
// Local scope shows: amount
// Closure scope shows: count, initialValue
count += amount;
return count;
}
return increment;
}Watch Expressions
The Watch panel lets you type any JavaScript expression and see its value update in real time as you step through code. Click the + icon to add:
cart.items.length
total > 100
user?.permissions?.includes('admin')
cart.items.filter(i => i.quantity > 5)
Watch expressions re-evaluate every time you step to a new line. They are perfect for monitoring computed values or conditions.
The Console During Breakpoints
When paused at a breakpoint, the Console panel has access to the current scope. You can:
- Type variable names to see their values
- Modify variables (e.g.,
total = 200) and then resume to test different paths - Call functions available in scope
- Evaluate complex expressions
This is more flexible than watch expressions because you can run arbitrary code.
Debugging Asynchronous Code
Async code (Promises, async/await, setTimeout) creates debugging challenges because the call stack resets between async operations:
async function loadUserDashboard(userId) {
const user = await fetchUser(userId); // Breakpoint 1
const posts = await fetchPosts(user.id); // Breakpoint 2
const stats = computeStats(posts); // Breakpoint 3
return { user, posts, stats };
}Async Call Stacks
Chrome DevTools shows async call stacks by default. When paused at breakpoint 2, the Call Stack panel shows not just the current synchronous stack, but also the chain of async operations that led here. This means you can trace back through await boundaries.
Debugging setTimeout and setInterval
function initializeApp() {
console.log('App starting...');
setTimeout(() => {
// Set a breakpoint inside the callback
loadConfiguration(); // Breakpoint here
}, 2000);
}When paused inside the setTimeout callback, the async call stack shows that the immediate caller is the timer system, but the "async" stack frame shows initializeApp as the originator.
Debugging Common Bug Patterns
Pattern 1: Variable Is undefined
When a variable is unexpectedly undefined, work backward:
function displayUserBadge(data) {
// data.user.profile.badge is undefined — but why?
debugger; // Pause here and inspect:
// In console, check each level:
// data → {user: {name: 'Alice', profile: null}}
// data.user → {name: 'Alice', profile: null}
// data.user.profile → null (!)
// That's the problem: profile is null, not an object
const badge = data.user.profile.badge; // TypeError: Cannot read properties of null
}Pattern 2: Function Called With Wrong Arguments
Use console.trace() or a breakpoint to see who called the function and with what:
function formatPrice(amount) {
debugger; // Pause and check: amount is "49.99" (string, not number)
return `$${(amount * 1.08).toFixed(2)}`; // NaN because string multiplication is unreliable
}
// The caller passed a string from a form input:
formatPrice(document.getElementById('price').value); // "49.99" not 49.99Pattern 3: Loop Off-by-One Error
Set a conditional breakpoint on the last iteration:
const items = ['apple', 'banana', 'cherry', 'date'];
for (let i = 0; i <= items.length; i++) {
// Conditional breakpoint: i >= items.length - 1
// This pauses on i=3 (last valid) and i=4 (out of bounds)
console.log(items[i]); // undefined on last iteration when i === 4
}The conditional breakpoint reveals that <= should be <.
Using the Network Panel for API Debugging
When your JavaScript makes API calls and the response is not what you expect, the Network panel shows exactly what was sent and received:
- Open DevTools, click the Network tab
- Trigger the API call
- Click the request in the list
- Check each tab:
| Tab | Shows |
|---|---|
| Headers | Request URL, method, status code, request/response headers |
| Payload | Request body (POST data, JSON) |
| Response | Raw response body from the server |
| Preview | Formatted/rendered response |
| Timing | DNS, connection, TLS, waiting, download timing |
This is often faster than debugging the JavaScript code itself, because you can immediately see whether the problem is in the request your code sent or the response the server returned.
Best Practices
Debugging Workflow Guidelines
These practices help you find bugs faster and avoid common time sinks.
Reproduce the bug before debugging. If you cannot reliably trigger the bug, you cannot verify your fix. Write down the exact steps, browser, and input data needed to reproduce it.
Start from the error, not the beginning. Read the error message and stack trace first. Set your breakpoint near where the error occurs, then work backward. Starting from the top of the code and stepping through everything wastes time.
Use binary search for large codebases. If you do not know where the bug is, place a breakpoint halfway through the suspected code path. Check if the data is correct at that point. If yes, the bug is after that point. If no, it is before. Repeat to narrow down quickly.
Keep the Console open while using Sources. Press Esc in the Sources panel to open a Console drawer at the bottom. This lets you evaluate expressions in the current scope without switching panels.
Clean up after debugging. Remove all debugger statements and console.log() calls before committing. Use ESLint rules no-debugger and no-console to catch missed ones.
Common Mistakes and How to Avoid Them
Debugging Pitfalls
These mistakes extend debugging sessions unnecessarily.
Guessing instead of inspecting. When a value is wrong, do not assume you know why. Pause execution and look at the actual value. Assumptions are wrong more often than you expect.
Adding too many log statements. If you need more than 5 console.log() calls to find a bug, switch to breakpoints. Breakpoints let you inspect everything in scope at once instead of logging individual values.
Ignoring the error message. JavaScript error messages are specific: TypeError: Cannot read properties of undefined (reading 'map') tells you exactly that something is undefined when it should not be. Read the message before looking at the code.
Not checking the Network panel. When an API call returns unexpected data, the bug might be on the server, not in your JavaScript. Always check the Network panel to verify what was sent and received before debugging the client code.
Forgetting that DevTools must be open for debugger to work. The debugger statement only pauses if browser DevTools is open. If the statement does not seem to work, press F12 first.
DevTools Keyboard Shortcuts Reference
| Action | Windows / Linux | Mac |
|---|---|---|
| Open DevTools | F12 or Ctrl+Shift+I | Cmd+Option+I |
| Open Console | Ctrl+Shift+J | Cmd+Option+J |
| Resume execution | F8 | F8 |
| Step over | F10 | F10 |
| Step into | F11 | F11 |
| Step out | Shift+F11 | Shift+F11 |
| Toggle breakpoint | Click line number | Click line number |
| Search across files | Ctrl+Shift+F | Cmd+Option+F |
| Go to file | Ctrl+P | Cmd+P |
| Clear console | Ctrl+L | Cmd+K |
Next Steps
Practice breakpoint debugging on a real project
Open one of your existing projects in Chrome, set breakpoints on 3 different functions, and step through the execution. Get comfortable with Step Over (F10), Step Into (F11), and watching the Scope panel update.
Learn to read stack traces
Master how to read and understand JavaScript stack traces so you can pinpoint the origin of errors without guessing.
Explore advanced DevTools features
Try the Performance panel (for slow code), Memory panel (for memory leaks), and Application panel (for cookies, localStorage, and service workers). Each panel solves a different debugging problem.
Set up error monitoring for production
Install an error tracking tool like Sentry or Bugsnag to catch errors in production. These tools capture stack traces, user context, and breadcrumbs automatically.
Rune AI
Key Insights
- Breakpoints beat console.log for complex bugs: set them in DevTools without changing code, add conditions, and inspect every variable in scope at once
- The debugger statement is a code-level breakpoint: use it when you know exactly where to pause, but always remove it before committing
- Step Over, Step Into, Step Out are your core tools: F10 moves forward, F11 dives into functions, Shift+F11 returns to the caller
- Check the Network panel for API issues: verify what was sent and received before debugging client-side logic
- Reproduce first, debug second: if you cannot trigger the bug reliably, you cannot verify your fix
Frequently Asked Questions
Is the debugger statement better than console.log()?
Can I debug JavaScript without Chrome DevTools?
How do I debug minified production code?
Do breakpoints slow down my application?
How do I debug code that only fails in production?
Can I change variable values while debugging?
Conclusion
Effective JavaScript debugging means moving beyond scattered console.log() statements to using the full power of browser DevTools. Breakpoints let you pause execution and inspect every variable in scope. Stepping controls let you walk through branching logic one line at a time. Watch expressions and conditional breakpoints let you monitor specific values without modifying your source code. Combined with the Network panel for API debugging and console.trace() for call path analysis, these tools turn a guessing game into a systematic, repeatable process.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.