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.

JavaScriptbeginner
14 min read

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:

javascriptjavascript
// 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:

javascriptjavascript
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:

javascriptjavascript
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 0

The 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:

javascriptjavascript
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()

ScenarioUseWhy
Check a single variable valueconsole.log()No need to pause execution
Inspect multiple variables in contextdebuggerSee all variables at once in the Scope panel
Step through branching logicdebuggerWalk through each condition manually
Check what a loop does on iteration 47debugger with conditionalCan't practically log 47 iterations
Quick check during developmentconsole.log()Faster than opening DevTools
Diagnose a complex state bugdebuggerNeed 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

MethodShortcut
Open DevToolsF12 or Ctrl+Shift+I (Windows) / Cmd+Option+I (Mac)
Open directly to SourcesCtrl+Shift+I then click "Sources" tab
Open Console drawer in SourcesEsc 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:

  1. It does not require changing your source code
  2. You can enable/disable breakpoints without editing
  3. You can set conditional breakpoints
  4. Breakpoints persist across page reloads

To set a breakpoint:

  1. Open DevTools (F12)
  2. Go to the Sources panel
  3. Navigate to your JavaScript file in the left panel
  4. 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:

javascriptjavascript
// 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:

CodeCode
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:

ButtonShortcutAction
ResumeF8Continue running until the next breakpoint
Step OverF10Execute the current line and move to the next line
Step IntoF11If the current line calls a function, go inside that function
Step OutShift+F11Finish the current function and pause at the caller

Practical Stepping Example

Consider this code with a bug (the discount calculation is wrong):

javascriptjavascript
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:

  1. Set a breakpoint on the line const discount = applyDiscount(...);
  2. Trigger the checkout function
  3. When paused, hover over total to verify it is correct
  4. Press F11 (Step Into) to go inside applyDiscount()
  5. Step through the if statements with F10 (Step Over)
  6. Verify the returned discount value
  7. Press Shift+F11 (Step Out) to return to the checkout function
  8. Hover over finalTotal and see it is total + discount instead of total - 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 window object (usually very large; rarely needed)
javascriptjavascript
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:

CodeCode
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:

javascriptjavascript
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

javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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.99

Pattern 3: Loop Off-by-One Error

Set a conditional breakpoint on the last iteration:

javascriptjavascript
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:

  1. Open DevTools, click the Network tab
  2. Trigger the API call
  3. Click the request in the list
  4. Check each tab:
TabShows
HeadersRequest URL, method, status code, request/response headers
PayloadRequest body (POST data, JSON)
ResponseRaw response body from the server
PreviewFormatted/rendered response
TimingDNS, 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

ActionWindows / LinuxMac
Open DevToolsF12 or Ctrl+Shift+ICmd+Option+I
Open ConsoleCtrl+Shift+JCmd+Option+J
Resume executionF8F8
Step overF10F10
Step intoF11F11
Step outShift+F11Shift+F11
Toggle breakpointClick line numberClick line number
Search across filesCtrl+Shift+FCmd+Option+F
Go to fileCtrl+PCmd+P
Clear consoleCtrl+LCmd+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

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
RunePowered by Rune AI

Frequently Asked Questions

Is the debugger statement better than console.log()?

Neither is universally better. `console.log()` is fastest for checking single values without stopping execution. The `debugger` statement (or breakpoints) is better when you need to inspect multiple variables, step through logic, or examine the call stack. Professional developers use both depending on the situation.

Can I debug JavaScript without Chrome DevTools?

Yes. Firefox Developer Tools, Edge DevTools, and Safari Web Inspector all provide similar debugging capabilities. For Node.js, you can use `node --inspect` with Chrome DevTools, VS Code's built-in debugger, or the `node inspect` command-line debugger.

How do I debug minified production code?

Use source maps. Most build tools (Webpack, Vite, Rollup) generate `.map` files that link minified code back to the original source. Chrome DevTools loads source maps automatically, letting you set breakpoints and read stack traces in your original, unminified code.

Do breakpoints slow down my application?

Only when they trigger. An active breakpoint pauses execution, which obviously stops the app. But untriggered breakpoints have negligible overhead. You can leave dozens of disabled breakpoints in DevTools without affecting performance.

How do I debug code that only fails in production?

dd error monitoring (Sentry, Bugsnag) to capture stack traces and context when errors occur. Use remote debugging for mobile browsers. For intermittent bugs, add structured logging at key decision points and review logs when the error occurs. Never use `debugger` statements in production.

Can I change variable values while debugging?

Yes. When paused at a breakpoint, you can modify variables in the Console panel (type `total = 200` and press Enter) or double-click a value in the Scope panel. The modified value persists for the rest of that execution. This lets you test fixes without editing code.

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.