JavaScript Debugging
Finding and fixing errors in your JavaScript code
๐ What is JavaScript Debugging?
Debugging is the process of finding and fixing errors (bugs) in your JavaScript code. Every developer needs to know how to debug effectively!
// This code has a bug - can you spot it?
function greetUser(name) {
console.log("Hello " + nam + "!"); // Typo: 'nam' instead of 'name'
}
greetUser("Alice");
Debugging Methods
Console.log()
Print values to see what's happening
Browser DevTools
Advanced debugging with breakpoints
Error Messages
Understanding JavaScript errors
Testing
Prevent bugs with tests
๐น Using Console.log()
The simplest way to debug is printing values to the console:
function calculateTotal(price, tax) {
console.log("Price:", price); // Debug: check input
console.log("Tax:", tax); // Debug: check input
let total = price + (price * tax);
console.log("Total:", total); // Debug: check result
return total;
}
let result = calculateTotal(100, 0.08);
console.log("Final result:", result);
Console Output:
Price: 100 Tax: 0.08 Total: 108 Final result: 108
๐น Common JavaScript Errors
Learn to recognize and fix common error types:
๐ธ Syntax Errors
// โ Missing closing bracket
function sayHello() {
console.log("Hello");
// SyntaxError: Unexpected end of input
// โ
Fixed version
function sayHello() {
console.log("Hello");
}
๐ธ Reference Errors
// โ Variable not defined
console.log(userName); // ReferenceError: userName is not defined
// โ
Fixed version
let userName = "Alice";
console.log(userName);
๐ธ Type Errors
// โ Calling method on undefined
let user;
console.log(user.name); // TypeError: Cannot read property 'name' of undefined
// โ
Fixed version
let user = { name: "Alice" };
console.log(user.name);
๐น Using Browser DevTools
Advanced debugging with browser developer tools:
How to open DevTools:
- Chrome/Edge: F12 or Ctrl+Shift+I
- Firefox: F12 or Ctrl+Shift+I
- Safari: Cmd+Option+I
๐ธ Setting Breakpoints
function processOrder(items) {
debugger; // This will pause execution here
let total = 0;
for (let item of items) {
total += item.price; // Set breakpoint here in DevTools
}
return total;
}
let order = [
{ name: "Book", price: 15 },
{ name: "Pen", price: 2 }
];
processOrder(order);
๐น Debugging Strategies
Effective approaches to find and fix bugs:
Step-by-Step Debugging:
- Read the error message - It tells you what's wrong
- Check the line number - Where the error occurred
- Add console.log() - See variable values
- Use breakpoints - Pause and inspect code
- Test small parts - Isolate the problem
๐ธ Debugging Example
// Bug: Function not working as expected
function findLargest(numbers) {
let largest = 0; // Bug: What if all numbers are negative?
for (let i = 0; i < numbers.length; i++) {
console.log(`Checking: ${numbers[i]}, Current largest: ${largest}`);
if (numbers[i] > largest) {
largest = numbers[i];
}
}
return largest;
}
// Test with negative numbers
console.log(findLargest([-5, -2, -8])); // Returns 0, should be -2
// Fixed version
function findLargestFixed(numbers) {
if (numbers.length === 0) return undefined;
let largest = numbers[0]; // Start with first number
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
return largest;
}
๐น Debugging Tools & Tips
Useful tools and techniques for better debugging:
๐ธ Console Methods
// Different console methods for different purposes
console.log("General info");
console.warn("Warning message");
console.error("Error message");
console.table([{name: "Alice", age: 25}, {name: "Bob", age: 30}]);
// Group related logs
console.group("User Processing");
console.log("Processing user data...");
console.log("Validation complete");
console.groupEnd();
๐ธ Try-Catch for Error Handling
function safeParseJSON(jsonString) {
try {
let data = JSON.parse(jsonString);
console.log("Parsing successful:", data);
return data;
} catch (error) {
console.error("JSON parsing failed:", error.message);
return null;
}
}
// Test with invalid JSON
safeParseJSON('{"name": "Alice"}'); // Works
safeParseJSON('invalid json'); // Handles error gracefully