Spex3
    

Debugging in JavaScript 🔍


    

    

Debugging in JavaScript 🔍
Debugging is the process of identifying and fixing errors in your code. JavaScript provides powerful developer tools in the browser to help debug efficiently.

1️⃣ Using Browser Developer Tools 🛠
Most modern browsers (Chrome, Firefox, Edge) have built-in Developer Tools (DevTools).

✅ Opening DevTools
Chrome/Edge: F12 or Ctrl + Shift + I (Windows/Linux) | Cmd + Option + I (Mac)

Firefox: Ctrl + Shift + I (Windows/Linux) | Cmd + Option + I (Mac)

2️⃣ Console Logging 🖥
The console.log() method is used to print output to the console.

✅ Basic Logging

 
console.log("Hello, Debugging!"); // Prints to the console


✅ Logging Variables

let name = "Alice";
console.log("User Name:", name);

✅ Logging Multiple Values

let a = 10, b = 20;
console.log("Values:", a, b);


✅ Logging Objects and Arrays

let user = { name: "Alice", age: 25 };
console.log(user);
console.table(user); // Displays data in a table


3️⃣ Console Methods 📌
Method Description Example
console.log() Logs messages console.log("Hello")
console.error() Logs errors console.error("Something went wrong!")
console.warn() Logs warnings console.warn("Be careful!")
console.info() Logs info messages console.info("This is info")
console.table() Displays tabular data console.table([{name: "Alice", age: 25}])
console.time() / console.timeEnd() Measures execution time console.time("test"); console.timeEnd("test");

4️⃣ Using Breakpoints 🛑
Instead of console.log(), you can pause code execution and inspect values.

✅ 1. debugger Statement

let num = 10;
debugger; // Pauses execution (if DevTools is open)
console.log(num);

When DevTools is open, execution will pause at debugger.

✅ 2. Setting Breakpoints in DevTools
Open DevTools (F12 or Ctrl + Shift + I).

Go to the "Sources" tab.

Click on the JavaScript file you want to debug.

Click on the line number to set a breakpoint.

Reload the page and watch execution pause.

5️⃣ Catching Errors with try...catch 🚨

try {
let result = x / 2; // `x` is undefined
} catch (error) {
console.error("Error:", error.message);
}


Prevents the script from crashing when an error occurs.

6️⃣ Summary 🏆
✔️ Use console.log(), console.error(), and console.table() for debugging.
✔️ Use the DevTools Console to inspect errors.
✔️ Use Breakpoints and the debugger statement to pause execution.
✔️ Handle errors using try...catch.


    Date: 2025-03-29 00:00:00.000000