01 / 20
!

Common JavaScript
Bugs

Learn to recognize and fix the sneakiest bugs in JavaScript: from undefined access to type coercion and async timing pitfalls.

JavaScript

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

Undefined Access
Reading properties from undefined or null values, causing runtime crashes.
Type Coercion
JavaScript silently converts types, producing unexpected results in comparisons and arithmetic.
Async Timing
Code runs out of order because callbacks, promises, or timeouts resolve later than expected.

Why JavaScript Is Bug-Prone

Dynamic Typing Variables can hold any type, anytime Implicit Coercion JS auto-converts types in operations Event Loop Single-threaded, non-blocking async undefined is not a function "5" + 3 = "53" not 8 Data arrives after code finishes Three language features that create the most common bugs

Undefined Access: The Core Rule

let user = undefined; // No error yet: user is just undefined console.log(user.name); // TypeError: Cannot read properties of undefined

Type Coercion: The Core Rule

"5" + 3 // "53" (string wins) "5" - 3 // 2 (coerced to number) "5" == 5 // true (loose equality coerces) "5" === 5 // false (strict: no coercion)

== 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

let data = "loading"; setTimeout(() => { data = "done"; }, 1000); console.log(data); // "loading" (NOT "done") // The timeout callback hasn't run yet!

The Event Loop in Action

Execution Timeline 1. Set data data = "loading" 2. setTimeout schedule for later 3. console.log prints "loading" Callback Queue (runs after main code) data = "done" executes here, 1000ms later Synchronous code always finishes before async callbacks run

How to Debug Effectively

1
Read the error message. The stack trace tells you the exact line, file, and type of error.
2
Check your types. Add console.log(typeof variable) before the failing line to see what the value actually is.
3
Trace execution order. Number your console.log statements to see if async code runs in the order you expect.
4
Isolate the problem. Comment out code until the bug disappears, then add it back line by line.
5
Prevent future bugs. Add defensive checks: optional chaining, strict equality, and async/await.

Example 1: Undefined Property Access

Buggy Code
function greet(user) { return "Hello, " + user.name.toUpperCase(); } greet({}); // TypeError! // user.name is undefined, then .toUpperCase() crashes
Fixed Code
function greet(user) { const name = user?.name ?? "stranger"; return "Hello, " + name.toUpperCase(); } greet({}); // "Hello, STRANGER"

Example 2: The Coercion Trap

Buggy Code
const price = "19.99"; // from user input const tax = 1.50; const total = price + tax; console.log(total); // "19.991.5" (string concatenation!)
Fixed Code
const price = Number("19.99"); // explicit conversion const tax = 1.50; const total = price + tax; console.log(total); // 21.49 (correct math!)

Example 3: Async Data Race

Buggy Code
let users = []; fetch("/api/users") .then(res => res.json()) .then(data => users = data); console.log(users.length); // 0 (fetch hasn't resolved yet!)
Fixed Code (async/await)
async function loadUsers() { const res = await fetch("/api/users"); const users = await res.json(); console.log(users.length); // Correct count! }

Common Mistakes to Avoid

✕ Using == Instead of ===
Loose equality hides type mismatches. "0" == false is true, which almost never reflects intent.
✕ Ignoring Return Values
Forgetting that .map(), .filter(), and async functions return new values. The original array is unchanged.
✕ No Null Checks
Assuming API data always has every field. A missing .address.city crashes the whole page.

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

What will console.log(x + y) output?

Question 2 of 5

What happens when this code runs?

Question 3 of 5

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

What is the best fix for this bug?