Common JavaScript
Bugs
Learn to recognize and fix the sneakiest bugs in JavaScript: from undefined access to type coercion and async timing pitfalls.
What Is a Bug?
A bug is any behavior in your code that differs from what you intended. In JavaScript, bugs are especially tricky because the language is dynamically typed and highly permissive: it often runs code without errors even when something is clearly wrong.
The Big Three Bug Families
Why JavaScript Is Bug-Prone
Undefined Access: The Core Rule
Type Coercion: The Core Rule
== vs ===: A Critical Distinction
| == (Loose) | === (Strict) | |
|---|---|---|
| Type coercion | Yes: converts before comparing | No: types must match |
| "0" vs 0 | true | false |
| false vs "" | true | false |
| null vs undefined | true | false |
| Bug risk | High | Low |
Async Timing: The Core Rule
The Event Loop in Action
How to Debug Effectively
Example 1: Undefined Property Access
Example 2: The Coercion Trap
Example 3: Async Data Race
Common Mistakes to Avoid
Bug Type Summary
| Bug Type | Symptom | Root Cause | Fix |
|---|---|---|---|
| Undefined Access | TypeError: Cannot read properties | Missing or null value | ?. and ?? |
| Type Coercion | Wrong result, no error | String + Number mix | === and Number() |
| Async Timing | Stale or empty data | Code runs before callback | await / .then() |
| Scope Issues | Variable is undefined | var hoisting, closures | Use const / let |
Question 1 of 5
Consider the following code:
let x = "10";
let y = 5;
console.log(x + y);
What will console.log(x + y) output?
Question 2 of 5
Consider the following code:
let obj = null;
console.log(obj.name);
What happens when this code runs?
Question 3 of 5
Consider the following code:
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");
What is the order of output?
Question 4 of 5
Which operator should you always use to avoid type coercion bugs in comparisons?
Question 5 of 5
Consider the following code:
const user = { profile: { name: "Alex" } };
console.log(user.settings.theme);
What is the best fix for this bug?