How to Debug Javascript from Google Chrome

Chrome DevTools is a powerful built-in tool for debugging JavaScript. Here's a complete guide:
1. Open Chrome DevTools
Method 1: Keyboard Shortcut
Windows/Linux: F12 or Ctrl + Shift + I
Mac: Cmd + Option + I
```
### **Method 2: Right-click Menu**
1. Right-click on the page
2. Select **Inspect** or **Inspect Element**
### **Method 3: Menu**
1. Click **⋮** (three dots) top-right
2. Select **More tools → Developer tools**
---
## **2. Console Tab**
The **Console** is where you can run JavaScript code directly and see errors.
### **View Errors**
```
1. Open DevTools → Console tab
2. Any JavaScript errors appear in red
3. Click on the error to see the file and line numberJavaScriptLog Messages
javascript
// In your code
console.log("Variable value:", myVar);
console.warn("Warning message");
console.error("Error message");
console.table(arrayOfObjects);JavaScriptRun Code Directly
javascript
// Type in Console and press Enter
5 + 5
// Output: 10
document.title = "New Title"
// Changes page title
fetch('https://api.example.com/data').then(r => r.json())
// Test API calls JavaScript3. Sources Tab (Main Debugging)
The Sources tab lets you set breakpoints and step through code.
Set a Breakpoint
Method 1: Click Line Number
- Go to Sources tab
- Open your JavaScript file
- Click on the line number where you want to break
- A blue dot appears (breakpoint set)
Method 2: In Code
javascript
// Add this to your code
debugger; // Execution pauses here when DevTools is open JavaScriptMethod 3: Conditional Breakpoint
- Right-click on line number
- Select Add conditional breakpoint
- Enter condition:
myVar === 5 - Breaks only when condition is true
4. Step Through Code
Once execution pauses at a breakpoint:
ButtonActionShortcutStep OverExecute next lineF10Step IntoEnter functionF11Step OutExit functionShift + F11ContinueResume executionF8
Example:
javascript
function calculateTotal(a, b) {
let sum = a + b; // Line 1 - Step into here
return sum * 2; // Line 2 - Step over
}
let result = calculateTotal(5, 3); // Pause here with breakpoint JavaScript5. Watch Variables
Monitor specific variables as you step through code.
Add Watch Expression
- In Sources tab, find Watch panel (right side)
- Click + to add expression
- Type variable name:
myVar - See its value update as you step through
Example:
javascript
let counter = 0;
for (let i = 0; i < 5; i++) {
counter += i; // Watch 'counter' value change
console.log(counter);
}JavaScript6. Scope Panel
See all variables in current scope while debugging.
javascript
function testScope() {
let localVar = 10;
const globalVar = 20;
var functionVar = 30;
debugger; // Pause here and check Scope panel
}
testScope();CodeQLScope Shows:
- Local - Variables in current function
- Closure - Variables from outer scope
- Global - Global variables
7. Call Stack
See the function call history (which functions called which).
javascript
function function1() {
function2();
}
function function2() {
function3();
}
function function3() {
debugger; // Call Stack shows: function3 → function2 → function1
}
function1();JavaScriptClick on stack items to jump to that function's code.
8. Network Tab (Debug API Calls)
Monitor network requests and responses.
View API Calls
- Open Network tab
- Make an API call (fetch, axios, etc.)
- See the request in the list
Inspect Request
javascript
fetch('https://jsonplaceholder.typicode.com/users/1')<br> .then(r => r.json())<br> .then(data => console.log(data));JavaScriptIn Network Tab:
- Headers - Request/response headers
- Preview - Formatted response data
- Response - Raw response
- Timing - How long request took
9. Breakpoint Types
Line Breakpoint (Pause on specific line)
javascript
function myFunc() {
let x = 5; // ← Set breakpoint here
return x * 2;
}JavaScriptConditional Breakpoint (Pause if condition true)
javascript
for (let i = 0; i < 100; i++) {
console.log(i); // Pause only when i === 50
}
// Right-click line → Add conditional breakpoint → i === 50
```
### **DOM Breakpoint** (Pause when element changes)
```
1. Go to Elements tab
2. Right-click element
3. Break on → Subtree modifications / Attribute modifications / Node removal
```
### **Event Listener Breakpoint**
```
1. Go to Sources tab
2. Right panel → Event Listener Breakpoints
3. Check "Click", "Submit", etc.
4. Pauses when event firesJavaScript10. Console Debugging Functions
javascript
let user = { name: "Alice", age: 30 };
// Basic log
console.log("User:", user);
// Styled log
console.log("%cHello", "color: red; font-size: 20px;");
// Table format
console.table([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]);
// Count occurrences
console.count("myLabel"); // myLabel: 1
console.count("myLabel"); // myLabel: 2
// Timer
console.time("timer");
// ... do something ...
console.timeEnd("timer"); // timer: 123.45ms
// Group logs
console.group("Group Name");
console.log("Message 1");
console.log("Message 2");
console.groupEnd();
// Assert
console.assert(user.age > 0, "Age must be positive");JavaScript11. Complete Debugging Example
javascript
function calculateDiscount(price, discountPercent) {
debugger; // Pause here
if (price < 0) {
console.error("Price cannot be negative");
return 0;
}
let discount = (price * discountPercent) / 100;
let finalPrice = price - discount;
console.log(`Original: $${price}, Discount: $${discount}, Final: $${finalPrice}`);
return finalPrice;
}
calculateDiscount(100, 20);JavaScriptDebug Steps:
- Open DevTools (F12)
- Go to Sources tab
- Reload page (F5)
- Execution pauses at
debugger - Use Step Over (F10) to go line by line
- Check Watch panel for variable values
- Press Continue (F8) to resume
12. Error Debugging
Find and Fix Errors
javascript
// This causes an error
let obj = { name: "John" };
console.log(obj.age.toUpperCase()); // Error: Cannot read property 'toUpperCase' of undefined JavaScriptSteps:
- Open Console tab
- See red error message
- Click on file name to go to error location
- Use debugger to understand what went wrong
- Fix the code
Better code:
javascript
let obj = { name: "John" };
if (obj.age) {
console.log(obj.age.toUpperCase());
} else {
console.log("Age is not defined");
}
```
---
## **13. Local Storage & Session Storage Debugging**
```
1. Open DevTools
2. Go to Application tab
3. Click Local Storage or Session Storage
4. See all stored data
5. Right-click to edit/deleteJavaScriptDebug in Console:
javascript
// View all local storage
console.table(localStorage); // Set value
localStorage.setItem("user", "Alice"); // Get value
console.log(localStorage.getItem("user"));// Remove value
localStorage.removeItem("user"); // Clear all
localStorage.clear();JavaScript14. Performance Debugging
Measure Execution Time
javascript
console.time("myTimer");
// Your code here
for (let i = 0; i < 1000000; i++) {
Math.sqrt(i);
}
console.timeEnd("myTimer");
// Output: myTimer: 23.45ms JavaScriptUsing Performance API
javascript
const start = performance.now();
// Code to measure
const result = expensiveCalculation();
const end = performance.now();
console.log(`Execution time: ${end - start}ms`);
```
---
## **15. Quick Tips & Tricks**
### **Pause on Exception**
```
Sources tab → Click pause icon with exclamation mark
Automatically pauses when error is thrown
```
### **Modify Variables During Debug**
```
1. Pause at breakpoint
2. In Console, type: myVar = 100
3. Press Enter
4. Continue execution with new value
```
### **Pretty Print Minified Code**
```
1. Go to Sources tab
2. Open minified file
3. Click {} (Pretty print) button at bottom
4. Code becomes readable
```
### **Filter Console Messages**
```
Console tab → Levels dropdown
Choose: All, Errors, Warnings, Info, VerboseJavaScriptCopy Object to Clipboard
javascript
let obj = { id: 1, name: "Alice" };
copy(obj); // Copies to clipboardJavaScript16. Common Debugging Scenarios
Scenario 1: Function Not Executing
javascript
// Problem: function not called
function myFunc() {
console.log("Function called");
}
// Solution: Add debugger or console.log
debugger; // Add breakpoint here
myFunc();JavaScriptScenario 2: Wrong Variable Value
javascript
// Problem: Variable has unexpected value
let sum = 0;
for (let i = 0; i < 5; i++) {
sum += i;
}
console.log(sum); // Check if correct
// Debug: Add Watch expression for 'sum' JavaScriptScenario 3: Async/Await Issues
javascript
async function fetchData() {
try {
debugger; // Pause before fetch
const response = await fetch('/api/data');
const data = await response.json();
debugger; // Pause after fetch
return data;
} catch (error) {
console.error("Error:", error);
}
}
fetchData();JavaScriptDebugging Checklist
✅ Open DevTools (F12) ✅ Go to Console tab to see errors ✅ Go to Sources tab to set breakpoints ✅ Use Step Over (F10) to execute line by line ✅ Watch variables using Watch panel ✅ Check Scope panel for variable values ✅ Use Call Stack to understand function flow ✅ Use Network tab for API debugging ✅ Add debugger; in code for quick pausing ✅ Use console.log() for temporary debugging
Practice Exercise
Create this HTML file and debug it:
html
<!DOCTYPE html><br>
<html>
<br>
<head>
<br>
<title>Debug Exercise</title>
<br>
</head>
<br>
<body>
<br> <button id="btn">Calculate</button><br>
<p id="result"></p>
<br><br> <script><br> function calculate() {<br> debugger; // Set breakpoint here <br> <br> let num1 = 10;<br> let num2 = 5;<br> let result = num1 / num2; // Wrong: should be addition <br> <br> document.getElementById('result').textContent = result;<br> console.log("Result:", result);<br> }<br><br> document.getElementById('btn').addEventListener('click', calculate);<br> </script><br>
</body>
<br>
</html>HTMLTry it:
- Click the button
- DevTools pauses at debugger
- Step through the code
- Find the bug (division instead of addition)
Chrome DevTools is extremely powerful! These are the most important debugging techniques you'll use daily. 🎯


