← Back to Tutorials

How to Debug JavaScript Code: Complete Guide

Master JavaScript debugging with console methods, browser DevTools, and proven techniques to find and fix bugs faster.

Why Debugging Matters

Debugging is an essential skill for every JavaScript developer. Whether you're a beginner or experienced programmer, you'll spend significant time finding and fixing bugs. Learning proper debugging techniques will make you more efficient and help you build better applications.

This comprehensive guide covers everything from basic console.log() to advanced debugging strategies used by professional developers.

Console Methods for Debugging

1. console.log() - Your Best Friend

The most common debugging method. Use it to print values and track code execution:

// Basic usage
console.log('Hello, debugging!'); // Log multiple values
const user = { name: 'John', age: 30 };
console.log('User:', user); // Log with labels for clarity
console.log('Before API call');
fetch('/api/data').then(data => { console.log('API response:', data);
});

2. console.error() - Highlight Errors

Use console.error() to make error messages stand out in red:

try { riskyOperation();
} catch (error) { console.error('Operation failed:', error);
}

3. console.table() - Visualize Data

Display arrays and objects in a readable table format:

const users = [ { name: 'Alice', age: 25, role: 'Developer' }, { name: 'Bob', age: 30, role: 'Designer' }, { name: 'Charlie', age: 28, role: 'Manager' }
];
console.table(users);

4. console.trace() - Track Execution Path

Show the stack trace to understand how your code was called:

function a() { b(); }
function b() { c(); }
function c() { console.trace('How did we get here?'); }
a(); // Shows the full call stack

5. console.time() - Measure Performance

Time how long operations take to execute:

console.time('Array processing');
const result = largeArray.map(item => item * 2);
console.timeEnd('Array processing');
// Output: Array processing: 2.345ms
The Debugger Statement

The debugger statement pauses code execution and opens browser DevTools automatically. It's like setting a breakpoint directly in your code:

function calculateTotal(items) { let total = 0; debugger; // Execution pauses here for (let item of items) { total += item.price; } return total;
}

Pro Tip:

Remember to remove debugger statements before deploying to production! They'll cause your app to pause for users.

Common JavaScript Bugs & Solutions

1. Undefined Variable Errors

Problem: Accessing a variable that doesn't exist or isn't defined yet.

// ❌ Wrong
console.log(userName); // ReferenceError // ✅ Correct
const userName = 'John';
console.log(userName);

2. Async/Await Pitfalls

Problem: Forgetting to await promises or not handling errors properly.

// ❌ Wrong
async function getData() { const data = fetch('/api/users'); // Missing await! console.log(data); // Promise, not actual data
} // ✅ Correct
async function getData() { try { const response = await fetch('/api/users'); const data = await response.json(); console.log(data); } catch (error) { console.error('Failed to fetch:', error); }
}

3. Array/Object Mutation Issues

Problem: Unintentionally modifying original arrays or objects.

// ❌ Wrong - mutates original
const numbers = [1, 2, 3];
const doubled = numbers;
doubled.push(4);
console.log(numbers); // [1, 2, 3, 4] - Oops! // ✅ Correct - creates new array
const numbers = [1, 2, 3];
const doubled = [...numbers, 4];
console.log(numbers); // [1, 2, 3] - Original unchanged
Debugging Best Practices
<div><div><h4>Use meaningful variable names</h4> <p>Clear names make it easier to spot bugs: use 'userEmail' not 'x'</p></div></div><div><div><h4>Add descriptive console logs</h4> <p>Instead of console.log(data), use console.log('User profile data:', data)</p></div></div><div><div><h4>Break down complex functions</h4> <p>Smaller functions are easier to test and debug individually</p></div></div><div><div><h4>Use browser DevTools effectively</h4> <p>Learn to set breakpoints, watch variables, and step through code</p></div></div><div><div><h4>Handle errors properly</h4> <p>Always use try-catch blocks for risky operations and async code</p></div></div><div><div><h4>Test edge cases</h4> <p>Check behavior with empty arrays, null values, and unexpected inputs</p></div></div>

Practice Debugging Online

Ready to practice these debugging techniques? Use our online JavaScript editor to write code, test it instantly, and see console output in real-time.