JavaScript · Lesson 31 / 32 · English
Debugging JavaScript
Understand the idea. Change the code. Build confidence with one focused experiment.
Read this lesson in தமிழ் ↗.
Start with the idea
Debugging is a process: reproduce the failure, inspect values, identify the first incorrect assumption, then verify the fix. Log inputs as well as results.
Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.
Step-by-step lesson notes
Debugging JavaScript
Debugging is the process of finding and fixing errors in your code. JavaScript has powerful built-in tools and browser DevTools to help.
The debugger Statement
function calculateTotal(items) {
let total = 0;
for (const item of items) {
debugger; // ← execution PAUSES here in DevTools
total += item.price;
}
return total;
}
// Open DevTools (F12) BEFORE calling the function
calculateTotal([{ price: 10 }, { price: 20 }]);Remember: Remove debugger statements before committing code. They have no effect if DevTools is closed.
Advanced console Techniques
// Named groups
console.group("📦 Order Processing");
console.log("Validating items...");
console.log("Calculating total...");
console.groupEnd();
// Count how many times a line is reached
for (let i = 0; i < 5; i++) {
console.count("loop"); // "loop: 1", "loop: 2" ...
}
console.countReset("loop");
// Trace the call stack
function a() { b(); }
function b() { console.trace("How did I get here?"); }
a(); // shows full call stack
// Styled output
console.log(
"%cError!",
"color: red; font-size: 20px; font-weight: bold"
);
// Log with labels (object shorthand trick)
const x = 10, y = 20;
console.log({ x, y }); // { x: 10, y: 20 } — shows variable names!Common JavaScript Errors
| Error | Cause | Fix |
|---|---|---|
| ReferenceError: x is not defined | Using variable before declaring | Declare with let/const/var |
| TypeError: x is not a function | Calling a non-function value | Check the variable type |
| TypeError: Cannot read properties of null | Accessing property of null/undefined | Add null check before access |
| SyntaxError: Unexpected token | Invalid JS syntax | Check for missing brackets or commas |
| RangeError: Maximum call stack exceeded | Infinite recursion | Add a base case to recursion |
Defensive Debugging Patterns
// 1. Type checking before use
function process(data) {
if (!Array.isArray(data)) {
console.error("Expected array, got:", typeof data, data);
return;
}
// safe to use data as array
}
// 2. Optional chaining for deeply nested access
const city = user?.address?.city ?? "Unknown";
// 3. Structured error logging
try {
const result = riskyOperation();
} catch (err) {
console.error("[riskyOperation] Failed:", {
message: err.message,
stack: err.stack,
input: someInput
});
}
// 4. Assert-style helpers during development
function assert(condition, message) {
if (!condition) throw new Error(`Assertion failed: ${message}`);
}
assert(Array.isArray(items), "items must be an array");A complete example
Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.
const input = "20";
console.log("input type:", typeof input);
const amount = Number(input);
console.log("numeric type:", typeof amount);
console.log("total:", amount + 5);Predict first. Reveal the expected result.
input type: string numeric type: number total: 25
Make one change. See what happens.
Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.
Wait for the editor to load, then load this example and press Run.
Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.
Put the idea to work
Practice challenge
Remove Number and predict the total.
Reveal the answer and reasoning
Without conversion, input + 5 produces "205". The type logs reveal why.
One mistake to avoid: Do not treat the last line of a stack trace as the root cause automatically. Read the error message and find the relevant application frame.
Your learning checkpoint
- Explain the example in your own words.
- Complete the challenge before revealing its answer.
- Describe the common mistake and how to avoid it.