Back to Blog

How to Debug JavaScript Code in the Browser

Learn essential debugging techniques for JavaScript. Master browser DevTools, console methods, and strategies for finding and fixing bugs.

JavaScriptDebuggingDevTools

How to Debug JavaScript Code in the Browser

Debugging is an essential skill for every developer. When your code doesn't work as expected, knowing how to find and fix bugs quickly will save you hours of frustration. In this guide, we'll cover the tools and techniques for debugging JavaScript effectively.

Using console Methods

The console is your first line of defense for debugging.

console.log()

The most basic debugging tool:

const user = { name: 'John', age: 30 };
console.log('User:', user);
console.log('Name:', user.name);

console.table()

Display arrays and objects in a table format:

const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 }
];
console.table(users);

console.group()

Group related logs together:

console.group('User Details');
console.log('Name:', user.name);
console.log('Age:', user.age);
console.groupEnd();

console.time()

Measure execution time:

console.time('Loop');
for (let i = 0; i < 1000000; i++) {
// Some operation
}
console.timeEnd('Loop'); // Output: Loop: 5.123ms

console.trace()

Show the call stack:

function first() {
second();
}

function second() {
third();
}

function third() {
console.trace('Trace from third');
}

first();

console.assert()

Log only if a condition is false:

const value = 5;
console.assert(value > 10, 'Value should be greater than 10');
// Only logs if assertion fails

Browser DevTools

Opening DevTools

  • Chrome/Edge: F12 or Ctrl+Shift+I (Cmd+Option+I on Mac)
  • Firefox: F12 or Ctrl+Shift+I
  • Safari: Cmd+Option+I

The Sources Panel

The Sources panel lets you:

  • View all loaded scripts
  • Set breakpoints
  • Step through code
  • Inspect variables

Setting Breakpoints

Click on a line number in the Sources panel to set a breakpoint. When code execution reaches that line, it pauses.

Types of breakpoints:

  • Line breakpoints — Pause at specific line
  • Conditional breakpoints — Pause only when condition is true
  • DOM breakpoints — Pause when DOM changes
  • Event listener breakpoints — Pause on specific events
  • XHR breakpoints — Pause on network requests

Stepping Through Code

When paused at a breakpoint:

  • Step Over (F10) — Execute current line, move to next
  • Step Into (F11) — Enter a function call
  • Step Out (Shift+F11) — Exit current function
  • Resume (F8) — Continue to next breakpoint

Watch Expressions

Add expressions to the Watch panel to monitor their values as you step through code.

Call Stack

The Call Stack panel shows the sequence of function calls that led to the current point. Click on any frame to inspect variables at that point.

Debugging in ProLiveEditor

ProLiveEditor has a built-in console that captures:

  • console.log()
  • console.warn()
  • console.error()
  • JavaScript errors

Open the console panel at the bottom to see output from your code.

Quick Debugging Tips in ProLiveEditor

// Add this to see what's happening
console.log('Before:', variable);

// Check if code reaches a certain point
console.log('Reached checkpoint 1');

// Log object contents
console.log(JSON.stringify(object, null, 2));

Common Debugging Strategies

1. Rubber Duck Debugging

Explain your code line by line (to a rubber duck, or just yourself). Often, saying the logic out loud reveals the bug.

2. Binary Search

If you have a long piece of code:

  • Add a log in the middle
  • Determine if the bug is before or after
  • Repeat until you find it

3. Check Assumptions

When debugging, verify:

  • Is the function being called?
  • Do variables have expected values?
  • Are conditions evaluating correctly?

4. Read Error Messages

JavaScript errors tell you:

  • What went wrong (ReferenceError, TypeError, etc.)
  • Where it happened (file and line number)
  • Why (the error message)

// Common errors:
// ReferenceError - variable doesn't exist
console.log(undefinedVariable);

// TypeError - wrong type or operation
null.toString();

// SyntaxError - invalid code structure
// let x = ;

5. Isolate the Problem

  • Create a minimal test case
  • Remove unrelated code
  • Test one thing at a time

The debugger Statement

Add debugger; to your code to create a breakpoint programmatically:

function processData(data) {
debugger; // Pauses here when DevTools is open
// Process data...
}

This is especially useful when:

  • You can't easily navigate to the code in DevTools
  • You want to conditionally break

function processItems(items) {
items.forEach((item, index) => {
if (index === 50) {
debugger; // Only pause on item 50
}
// Process item...
});
}

Debugging Asynchronous Code

Async code can be tricky to debug. Here are some tips:

Promises

fetchData()
.then(data => {
console.log('Received:', data);
return processData(data);
})
.then(result => {
console.log('Processed:', result);
})
.catch(error => {
console.error('Error:', error);
});

Async/Await

async function loadData() {
try {
console.log('Starting fetch...');
const response = await fetch('/api/data');
console.log('Response:', response);

const data = await response.json();
console.log('Data:', data);

return data;
} catch (error) {
console.error('Failed:', error);
throw error;
}
}

Best Practices

  • Remove debug code before committing — Don't leave console.log statements in production
  • Use meaningful log messages — Include context in your logs
  • Learn the DevTools — Invest time in learning your browser's debugging tools
  • Write testable code — Small, focused functions are easier to debug
  • Use version control — If something breaks, you can compare with working code

Practice these techniques in ProLiveEditor. The built-in console makes it easy to debug and learn JavaScript interactively!

Try the Examples

Practice what you've learned with ProLiveEditor's live code editor.

Open Editor
PE
ProLiveEditor Team Building tools to help developers learn and create.