Debugging is like playing detective: “it’s not working!” isn’t enough, you need to understand the crime! The browser console is your magnifying glass, errors are clues, and AI is your Watson helping you solve the case. You’ll learn to transform “help, nothing works!” into “at line 42 it says undefined“, to read errors as messages (not insults), and to ask AI questions that lead to real solutions. Sherlock Holmes would be proud of you!
🧠 Does debugging scare you? That’s normal! But it’s by fixing errors that you learn the most!
Imagine you’re a detective called to a crime scene (your code that doesn’t work).
Confused witness: “There was this guy, he did something… now nothing works!”
Detective: “…” 🤷♂️
Prepared witness: “At 3:42 PM, at line 23, a man with a red hat (variable ‘user’) tried to enter a house that doesn’t exist (property ‘name’ of undefined)”
Detective: “Elementary! The ‘user’ variable is empty!” 🧐
It’s like opening a car’s dashboard: scary at first, but then you understand that every light has a meaning!
// 🟢 Console.log - Your notebook
console.log("Checkpoint 1: I'm here!"); // Mark where you've arrived
console.log("Value of x:", x); // Check what a variable contains
// 🟡 Console.warn - Yellow warning post-it
console.warn("Warning: the array is empty!"); // Important warnings
// 🔴 Console.error - Red alert!
console.error("ERROR: Division by zero!"); // Serious problems
// 🔵 Console.table - The organized report
let suspects = [
{ name: "Mario", alibi: "sleeping" },
{ name: "Luigi", alibi: "I was at the café" },
];
console.table(suspects); // Shows a nice table!
// BAD: The detective shouting every thought
console.log("1");
console.log("2");
console.log("here");
console.log("test");
console.log("whatever");
// Who's talking? About what? Why?
// GOOD: The detective taking clear notes
console.log("🔍 Starting user search");
console.log("📋 Data received:", userData);
console.log("✅ User found:", user.name);
You’ll realize over time this is the most common: above you wrote “hello”, but below you wrote “helo”.
// The criminal always leaves traces!
functio greet() { // ❌ "functio" instead of "function"
console.log("Hello")
}
// SyntaxError: Unexpected identifier
// AI understands immediately: "You wrote 'functio' instead of 'function' at line X"
// Looking for something that doesn't exist
console.log(ghostVariable); // ❌ Never declared!
// ReferenceError: ghostVariable is not defined
// AI will tell you: "You're using a variable you never created"
// Like using a screwdriver to hammer a nail
let number = 42;
number.push(1); // ❌ push is for arrays, not numbers!
// TypeError: number.push is not a function
// AI explains: "push() only works with arrays, not with numbers"
// The sneakiest criminal: makes no noise!
// CRIME SCENE
let user; // The main suspect (empty variable)
console.log(user.name); // 💥 ERROR: Cannot read property 'name' of undefined
// INVESTIGATION
console.log("Who is user?", user); // undefined! There's the culprit!
TypeError: Cannot read property 'name' of null
at getUserName (app.js:42:17) ← The problem is here!
at displayProfile (app.js:15:22) ← Called from here
at HTMLButtonElement.onclick (index.html:8) ← Everything started here
Read from bottom to top: it’s the crime trail!
🚫 WRONG
"the code doesn't work"
"I have an error"
"javascript sucks"
"why does it crash?"
"fix the bug"
✅ RIGHT
"I have this error in the console:
TypeError: Cannot read property 'map' of undefined
at renderTodos (app.js:23:15)
at HTMLButtonElement.onclick (index.html:12)
It happens when I click the 'Show Todo' button.
Here's the relevant code:
[paste lines 20-25 of app.js]
I expected it to show the list, but it crashes instead."
"I'm getting this error:
[paste the exact error from the console]
In the code:
[paste 5-10 lines around the error]
It happens when: [describe the action]
I expected: [what should have happened]
Can you explain why it happens and how to fix it?"
"My code doesn't give errors but doesn't do what I want:
Code:
[paste the problematic function]
Current behavior: [what happens]
Desired behavior: [what should happen]
I tried: [what you've already attempted]
Where am I going wrong?"
"Help me debug step by step:
1. I have this function: [code]
2. When I call it with this data: [example]
3. I expect: [expected result]
4. But I get: [actual result]
Guide me with console.log to understand where it breaks"
function calculateTotal(cart) {
console.log("🏁 START calculateTotal");
console.log("📦 Cart received:", cart);
let total = 0;
console.log("💰 Initial total:", total);
for (let item of cart) {
console.log("🛒 Processing item:", item);
total += item.price * item.quantity;
console.log("💵 Partial total:", total);
}
console.log("✅ END calculateTotal, final total:", total);
return total;
}
Like Hansel and Gretel: leave breadcrumbs to find your way back!
Explain the code to a rubber duck (or to AI 😅): The concept of this technique is to “tell” your code out loud, explaining what’s inside and what it should do. Often by re-reading it and “explaining” it aloud to someone (or something), you realize the flaw that creates the error yourself.
"So, let me explain what my code should do:
1. Take the array of numbers
2. Filter them to keep only even ones
3. Multiply them by 2
4. Sum them all
But the result is always 0.
Here's what the code does:
[explain out loud]
But while I'm explaining it to you, now that I think about it I realize... ah, there's the error!"
function problematic() {
// operation1(); // ✅ Works
// operation2(); // ✅ Works
operation3(); // 💥 If you uncomment only this and it crashes, found it!
// operation4();
}
// Instead of debugging all this:
let result = array
.filter((x) => x > 0)
.map((x) => x * 2)
.reduce((a, b) => a + b, 0);
// Split into pieces:
let step1 = array.filter((x) => x > 0);
console.log("After filter:", step1);
let step2 = step1.map((x) => x * 2);
console.log("After map:", step2);
let step3 = step2.reduce((a, b) => a + b, 0);
console.log("After reduce:", step3);
If you have your browser’s Developer Tools open, you can use debugger to put “stop points” in your code. Execution will stop at every checkpoint you’ve set and you can verify what the code does step by step, as if you were watching a movie in slow motion.
function complexCalculation(data) {
let result = data * 2;
debugger; // ⏸️ FREEZE! Code stops here
// Now you can inspect everything in the console:
// - Value of 'data'
// - Value of 'result'
// - Execute step-by-step
return result + 10;
}
It’s like pausing a movie to see the details of a scene and proceed frame by frame!
The undeclared variables we’ve already seen above.
// PROBLEM
let number = 42;
number.forEach((n) => console.log(n)); // 💥 forEach is for arrays!
// DEBUGGING
console.log("Type of number:", typeof number); // "number"
console.log("Is it an array?", Array.isArray(number)); // false
// SOLUTION
// Make sure it's an array before using array methods
// PROBLEM
while (i < 10) {
console.log(i);
// Oops, forgot i++ ! 😱
}
// TRICK: Always add a safety counter
let safety = 0;
while (i < 10 && safety < 1000) {
console.log(i);
safety++;
// If you forget i++, at least you won't freeze the browser
}
Cryptic error: “Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)”
Ask AI: “Translate this error into simple English and tell me the most common causes”
AI response: “You’re trying to use .map() on something that doesn’t exist. Probably:
"This code works but seems strange to me:
[paste code]
Do you see potential problems or hidden bugs?"
"I have this function:
[paste function]
Generate 5 test cases that could break it,
including edge cases and weird inputs"
Hi! I have this code that should manage a shopping list,
but it has various bugs. Help me debug it step by step:
```html
<!DOCTYPE html>
<html>
<head>
<title>Buggy Shopping List</title>
</head>
<body>
<h1>Shopping List</h1>
<input id="item" placeholder="What to buy?">
<button onclick="add()">Add</button>
<ul id="list"></ul>
<script>
let shoppingList = null; // Bug 1: should be array
function add() {
let item = document.getElementById('item').value;
shoppingList.push(item); // Bug 2: push on null
showList();
}
function showList() {
let ul = document.getElementById('list');
ul.innerHTML = '';
for (i = 0; i <= shoppingList.length; i++) { // Bug 3: <= instead of <
let li = document.createElement('li');
li.textContent = shoppingList[i].toUpperCase(); // Bug 4: undefined.toUpperCase()
ul.appendChild(li);
}
}
</script>
</body>
</html>
DO NOT fix immediately! Guide me through debugging:
1. What happens when I click "Add"?
2. What errors do I see in the console?
3. How do I use console.log to understand the problems?
4. Let's solve one bug at a time
Perfect! I clicked "Add" and got this error:
"TypeError: Cannot read property 'push' of null"
Help me:
1. Understand why shoppingList is null
2. Add console.log to verify
3. Fix ONLY this error
4. Explain what was happening
OK, now it doesn't crash immediately but I have a new error:
"TypeError: Cannot read property 'toUpperCase' of undefined"
Let's guide ourselves with console.log:
1. Where to put logs to understand the problem?
2. Why is an element undefined?
3. How do I fix this specific bug?
Now it works! But I want to improve debugging:
1. Add strategic console.logs that always help me
2. Add checks to prevent future errors
3. Show me how to use the debugger statement
4. Add a "debug mode" function I can activate
Explain every technique you use!
Last step! Create an "error handler" that:
1. Intercepts ALL JavaScript errors
2. Shows them in a red div on the page (not just console)
3. Suggests possible solutions for common errors
4. Has a "Copy error for AI" button that prepares the perfect text
Example: if it sees "undefined", suggests "Check if the variable exists"
It’s not:
It’s instead:
And most importantly, the most important rule: Celebrate when you solve it, because you’ve learned something!
Before moving to the next module:
If you’ve checked everything → Congratulations Detective! 🕵️ No bug will scare you anymore
If something isn’t clear → Normal! Debugging is an art that improves with practice (and asking AI).
In Module 10 we’ll talk about deployment: how to put your creation online! From localhost to the whole world, your custom domain, and those little things called privacy and security (with a wink, not with fear).
Remember: Even senior programmers spend 50% of their time debugging. The difference? They know it’s normal and have the right tools. Now you have them too!
Fun fact: The first computer “bug” was literally an insect! In 1947, Grace Hopper found a moth in the Harvard Mark II computer. Since then, all errors are called “bugs”! 🐛