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

Simple Quick Effective
๐Ÿ”

Browser DevTools

Advanced debugging with breakpoints

Chrome Firefox Safari
โš ๏ธ

Error Messages

Understanding JavaScript errors

Syntax Runtime Logic
๐Ÿงช

Testing

Prevent bugs with tests

Unit Tests Integration Manual

๐Ÿ”น 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:

  1. Read the error message - It tells you what's wrong
  2. Check the line number - Where the error occurred
  3. Add console.log() - See variable values
  4. Use breakpoints - Pause and inspect code
  5. 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

๐Ÿง  Test Your Knowledge

What does console.log() do in JavaScript?