Debugging

Back

Loading concept...

🔍 JavaScript Debugging: Becoming a Code Detective

The Story of the Code Detective

Imagine you’re a detective 🕵️ and your code is like a big house with many rooms. Sometimes things go wrong inside the house—a lamp doesn’t turn on, or a door won’t close. Your job is to find out what went wrong and where.

JavaScript gives you special detective tools called debugging tools. Let’s learn how to use them!


🎯 What You’ll Learn

  1. Console methods – Your detective notebook
  2. Debugger statement – Freezing time to investigate
  3. globalThis object – The master key to everything

📓 Console Methods: Your Detective Notebook

What is the Console?

Think of the console like a detective’s notebook. You write clues in it while your code runs. It helps you see what’s happening inside your program.

Opening Your Notebook

In any web browser, press F12 (or right-click → Inspect → Console). That’s your detective notebook!

The Most Important Console Methods

1. console.log() – Writing Notes

This is like writing a simple note in your notebook.

let name = "Alex";
console.log("The name is:", name);
// Output: The name is: Alex

Use it when: You want to see what value a variable holds.

2. console.error() – Red Alert! 🚨

When something bad happens, mark it in RED.

console.error("Oops! Something broke!");
// Shows red text in console

Use it when: You want to highlight a serious problem.

3. console.warn() – Yellow Caution ⚠️

Not as bad as an error, but still worth noting.

console.warn("Be careful here!");
// Shows yellow text in console

Use it when: Something might cause problems later.

4. console.table() – Organized Clues 📊

When you have a list of things, show them in a nice table.

let fruits = [
  { name: "Apple", color: "Red" },
  { name: "Banana", color: "Yellow" }
];
console.table(fruits);

Output:

Index name color
0 Apple Red
1 Banana Yellow

Use it when: You have arrays or objects to inspect.

5. console.group() – Folder for Clues 📁

Group related notes together.

console.group("User Details");
console.log("Name: Alex");
console.log("Age: 25");
console.groupEnd();

Use it when: You have many related messages.

6. console.time() & console.timeEnd() – Stopwatch ⏱️

Measure how long something takes.

console.time("Loop Timer");
for (let i = 0; i < 1000; i++) {
  // doing stuff
}
console.timeEnd("Loop Timer");
// Output: Loop Timer: 2.5ms

Use it when: You want to see if code is slow.

7. console.count() – Counting Visits

Count how many times code runs.

function greet() {
  console.count("greet called");
}
greet(); // greet called: 1
greet(); // greet called: 2
greet(); // greet called: 3

Use it when: You want to count function calls.

8. console.clear() – Clean Slate 🧹

Erase everything in the console.

console.clear();
// Console is now empty

⏸️ Debugger Statement: Freezing Time

The Magic Word: debugger

Imagine you could freeze time and look around your code. That’s exactly what debugger does!

When JavaScript sees the word debugger, it stops right there (if browser DevTools is open).

How It Works

let score = 0;

function addPoints(points) {
  debugger; // CODE STOPS HERE!
  score = score + points;
  return score;
}

addPoints(10);

When this runs (with DevTools open):

  1. Code freezes at debugger
  2. You can see all variables
  3. You can step through line by line

Your Detective Controls

When code is frozen, you get these buttons:

▶️ Resume    = Continue running
⏭️ Step Over = Go to next line
⬇️ Step Into = Go inside function
⬆️ Step Out  = Exit current function

Real Example: Finding a Bug

function calculateTotal(price, quantity) {
  debugger; // Freeze here!
  let total = price * quantity;
  let tax = total * 0.1;
  let final = total + tax;
  return final;
}

calculateTotal(100, 2);

When frozen, you can check:

  • Is price correct? ✅
  • Is quantity correct? ✅
  • Is tax calculated right? ✅

When to Use Debugger

Situation Use debugger?
Code gives wrong answer ✅ Yes
You’re confused about order ✅ Yes
Quick value check Use console.log

🌍 globalThis: The Master Key

What is globalThis?

Imagine a master key that opens every door in every building. globalThis is like that—it gives you access to the global object no matter where you are.

The Problem It Solves

JavaScript runs in different places:

  • Browser → global object is window
  • Node.js → global object is global
  • Web Workers → global object is self

Before globalThis, you had to check which one to use!

The Simple Solution

// Works EVERYWHERE!
console.log(globalThis);

In a browser, globalThis === window (true!)

What’s Inside globalThis?

// Some things you'll find:
globalThis.console    // The console object
globalThis.setTimeout // Timer function
globalThis.Math       // Math functions
globalThis.JSON       // JSON tools

Creating Global Variables

// Method 1: Direct assignment
globalThis.myApp = {
  version: "1.0",
  name: "Cool App"
};

// Now accessible everywhere!
console.log(globalThis.myApp.name);
// Output: Cool App

Real-World Example

// Check if running in browser
if (globalThis.window) {
  console.log("Running in browser!");
} else {
  console.log("Running in Node.js!");
}

Quick Comparison

graph TD A["globalThis"] --> B["Browser: window"] A --> C["Node.js: global"] A --> D["Web Workers: self"] style A fill:#667eea,color:#fff

Why Use globalThis?

Old Way New Way
Check for window Just use globalThis
Check for global Just use globalThis
Write extra code One word works everywhere

🎯 Putting It All Together

The Complete Detective Toolkit

// 1. Log clues
console.log("Investigating...");

// 2. Freeze time when needed
function suspiciousFunction(data) {
  debugger; // Stop and look around
  return data * 2;
}

// 3. Access global things
console.log(globalThis.location?.href);

Detective Workflow

graph TD A["Bug Found!"] --> B["Add console.log"] B --> C{Found the problem?} C -->|No| D["Add debugger"] D --> E["Step through code"] E --> F["Fix the bug!"] C -->|Yes| F style F fill:#4CAF50,color:#fff

💡 Quick Tips

  1. Start with console.log() – Most bugs are found this way
  2. Use debugger for tricky bugs – When you need to step through
  3. console.table() for arrays – Much easier to read!
  4. globalThis for universal code – Works everywhere

🎉 You’re Now a Code Detective!

You learned:

  • ✅ Console methods to write clues
  • ✅ Debugger to freeze and investigate
  • ✅ globalThis to access global features

Remember: Every great programmer spends time debugging. These tools make it easier and even fun!

Happy debugging, detective! 🕵️‍♀️🔍

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.