The Mystery of the Vanishing Values
Ugh, my code is broken AGAIN! I swear the interpreter just has it out for me. Maybe if I just add more features it'll magically fix itself!
ABSOLUTE AMATEUR HOUR! Have you even TRIED console logging? EVERY. SINGLE. VARIABLE should be console logged! 37 TIMES if necessary! HOW ELSE will you know what your code is DOING?!
Actually, strategic console logging can help pinpoint issues. Let's be methodical about this and check the value at each step of the process.
You know what would solve this? My premium "Bug Buster Pro" package. Exclusive error messages with extra emojis. Debugging should feel luxurious!
Um, I think I might have found something... There's a typo in the variable name. It's, uh, 'scroe' instead of 'score'...
A TYPO? Impossible! My fingers are guided by the cosmic energies of perfect code! It must be a browser conspiracy!
console.log(). It's not glamorous. Not exciting. But it works. Find what's broken. Fix it. Move on.
Just make sure you remove all those console.log() statements before production. I don't need another meeting explaining to the board why our site is leaking sensitive debugging data.
*woofs authoritatively*
(Translation: Today we learn how to use console.log() to find errors in our code. No treats until you've fixed all the bugs!)
Console Logging: Your Debugging Superpower
When your code doesn't behave as expected, console.log() becomes your best friend. This simple method lets you peek inside your code's execution to see what's really happening.
// Basic log - General information
console.log("This is a regular log message");
// Error log - For serious issues
console.error("Something went wrong!");
// Warning log - For potential problems
console.warn("This might cause issues later");
// Info log - For noteworthy details
console.info("Just so you know...");
Strategic Console Logging
As Ally suggested, strategic placement of console.log() calls helps track down bugs efficiently:
function calculateTotal(prices) {
console.log("Starting calculation with prices:", prices);
let total = 0;
console.log("Initial total:", total);
for (let i = 0; i < prices.length; i++) {
total += prices[i];
console.log(`After adding price at index ${i}:`, total);
}
const discount = total * 0.1; // 10% discount
console.log("Discount amount:", discount);
const final = total - discount;
console.log("Final total after discount:", final);
return final;
}
This step-by-step logging helps you trace the execution flow and pinpoint exactly where things go wrong.
Advanced Console Techniques
The console object has more tricks than just log():
// Group related logs
console.group("User Authentication");
console.log("Checking credentials...");
console.log("Access granted!");
console.groupEnd();
// Time operations
console.time("dataProcessing");
// ... some time-consuming operation
console.timeEnd("dataProcessing"); // "dataProcessing: 1234ms"
// Display data in a table
const users = [
{name: "Alice", score: 95},
{name: "Bob", score: 87},
{name: "Charlie", score: 92}
];
console.table(users);
Common Debugging Scenarios
1. Type Errors
// The bug: Trying to perform math on a string
let score = "10";
let bonus = 5;
let finalScore = score + bonus;
console.log(finalScore); // Outputs: "105" (string concatenation)
// Debugging with console.log
console.log("score:", score, "type:", typeof score);
console.log("bonus:", bonus, "type:", typeof bonus);
// Fix: Convert string to number
score = Number(score);
finalScore = score + bonus;
console.log(finalScore); // Outputs: 15 (numeric addition)
2. Reference Errors
// The bug: Using a variable before declaring it
console.log(username); // ReferenceError: username is not defined
let username = "player1";
// Debugging approach
try {
console.log(username);
} catch (error) {
console.error("Error caught:", error.message);
// Error caught: username is not defined
}
3. Logic Errors
// The bug: Logic error in condition
function isEligible(age, hasPermission) {
if (age >= 18 || hasPermission) { // Using OR instead of AND
return "Access granted";
} else {
return "Access denied";
}
}
// Debugging with console.log
const age = 16;
const hasPermission = false;
console.log("Age:", age, "Has Permission:", hasPermission);
console.log("Age >= 18:", age >= 18);
console.log("Result:", isEligible(age, hasPermission));
Bug Hunt: Find the Errors
Now it's your turn! Each of these code snippets contains at least one bug. Use console.log() to help identify and fix the issues.
Challenge 1: The Disappearing Score
This function should calculate a player's total score, but something's wrong. The final score is not what we expect!
function calculatePlayerScore(basePoints, bonusPoints, multiplier) {
let baseScore = basePoitns; // Bug: typo in variable name
let bonus = bonusPoints;
let total = baseScore + bonus;
return total * multiplier;
}
const playerScore = calculatePlayerScore(100, 50, 2);
console.log("Player's final score:", playerScore);
Challenge 2: The Discount Calculator
This function should apply a discount to a price, but customers are complaining about incorrect totals!
function applyDiscount(price, discountPercentage) {
const discount = price * discountPercentage; // Bug: not converting percentage to decimal
const finalPrice = price - discount;
return finalPrice;
}
const originalPrice = 80;
const discountPercent = 25; // 25% discount
const salePrice = applyDiscount(originalPrice, discountPercent);
console.log(`Original price: $${originalPrice}, Sale price: $${salePrice}`);
Challenge 3: The Broken Counter
This counter should increment up to a maximum value, then stop. But it's not behaving correctly!
function createCounter(maxValue) {
let count = 0;
return {
increment() {
if (count <= maxValue) { // Bug: increments one too many times
count++;
return count;
} else {
return count;
}
},
getCount() {
return count;
}
};
}
const counter = createCounter(3);
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.increment()); // 3
console.log(counter.increment()); // Should stay at 3, but returns 4
console.log(counter.getCount()); // Should be 3, but is 4
Debug Playground
Try fixing this code yourself. Use console.log to find and fix the bugs!
Debugging Best Practices
DO
- Log variables to check their current values
- Use descriptive labels in your console.log statements
- Log before and after critical operations
- Check data types when debugging calculation issues
- Group related logs for better readability
- Remove debug logs before production deployment
- Use console.error() for actual errors
DON'T
- Leave console.log() statements in production code
- Log sensitive information (passwords, tokens)
- Rely solely on console.log() for complex debugging
- Forget to check browser compatibility for advanced console methods
- Log huge objects without filtering relevant properties
- Use console.log() as a substitute for proper error handling
- Overuse logging to the point of performance impact
GrumpyMcTweak's DEBUGGING CHECKLIST OF DOOM
- HAVE YOU CHECKED THE VARIABLE TYPES? THEY'RE PROBABLY WRONG!
- IS THERE A TYPO? THERE'S ALWAYS A TYPO!
- HAVE YOU CONSOLE LOGGED EVERY SINGLE VALUE? IF NOT, WHY NOT?
- CHECK YOUR LOOP CONDITIONS! THEY'RE OFF BY ONE! THEY'RE ALWAYS OFF BY ONE!
- MISSING SEMICOLON? EXTRA SEMICOLON? SEMICOLONS ARE CHAOS!
- DID YOU MISUSE = AND ==? OF COURSE YOU DID!
- SCOPE ISSUES! IT'S ALWAYS SCOPE ISSUES!
Remember, console.log() is like a flashlight in a dark room - it helps you see what's really going on in your code. Use it strategically to illuminate the path to a solution!
Fine, I admit it! The console is... actually useful. But I'll never admit that in front of Grumpy! And I'm still going to claim my bugs are cosmic anomalies when anyone else is listening.
I made a little cheat sheet of common console methods to help with debugging. I hope it's useful...
Cody's Console Cheat Sheet
| Method | Usage | Example |
|---|---|---|
| console.log() | General information | console.log("Player score:", score); |
| console.error() | Error messages | console.error("Failed to load data!"); |
| console.warn() | Warning messages | console.warn("Deprecated function used"); |
| console.table() | Display tabular data | console.table(users); |
| console.group() | Group related logs | console.group("User Data"); |
| console.time() | Time operations | console.time("function"); // code... console.timeEnd("function"); |
*approving woofs*
(Translation: Debugging approved! Now you can find and fix errors in your code instead of blaming the browser, cosmic rays, or whatever excuse Trashy was going to invent next. Debug responsibly!)
What's Next?
Now that you've mastered console logging and debugging, you're ready to explore more advanced JavaScript concepts.
In our next session, we'll learn about conditionals with if/else statements, which will let your code make decisions based on different conditions.