Common JavaScript Bugs & How to Fix Them
Every JavaScript developer encounters the same bugs. Learn to recognize and fix the most common ones — from type coercion to scope issues to async timing problems.
Common Bugs
- == instead of === — '5' == 5 is true (unexpected). Always use ===
- Missing return — Function returns undefined if you forget return
- Mutating vs creating — sort() mutates original. Use [...arr].sort() for safety
- Async loop — for loop with setTimeout/await: use let, not var (closure bug)
- Off-by-one — array[array.length] is undefined. Last item: array[array.length - 1]
- this in callbacks — Arrow functions fix: setTimeout(() => this.save(), 1000)
- Floating point — 0.1 + 0.2 !== 0.3 (it's 0.30000000000000004). Use toFixed() or integer math
Common Bugs Code
// Bug 1: == vs ===
console.log("5" == 5); // true ← unexpected!
console.log("5" === 5); // false ← correct
// Fix: ALWAYS use ===
// Bug 2: Missing return
function double(n) {
n * 2; // ❌ forgot 'return'!
}
console.log(double(5)); // undefined (not 10!)
// Fix: return n * 2;
// Bug 3: Mutating arrays
const scores = [30, 10, 50, 20];
scores.sort(); // ❌ mutates AND sorts as strings!
console.log(scores); // [10, 20, 30, 50] — original changed!
// Fix: [...scores].sort((a, b) => a - b)
// Bug 4: var in loops (closure bug)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var:", i), 100);
}
// Prints: 3, 3, 3 (not 0, 1, 2!) — var is function-scoped
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log("let:", j), 100);
}
// Prints: 0, 1, 2 ✅ — let is block-scoped
// Bug 5: Floating point
console.log(0.1 + 0.2); // 0.30000000000000004 ❌
console.log(0.1 + 0.2 === 0.3); // false!
// Fix: use toFixed or integer math
console.log((0.1 + 0.2).toFixed(1) === "0.3"); // true
// Or: work in cents: 10 + 20 === 30 ✅
// Bug 6: typeof null
console.log(typeof null); // "object" ❌ (JS historical bug)
// Fix: check with === nullTip
Tip
90% of JavaScript bugs fall into these categories: off-by-one errors, null/undefined access, wrong 'this' context, async timing issues, and type coercion surprises. Learn to recognize these patterns quickly.
Use console.table for objects. console.time to profile. debugger; for breakpoints. Chrome DevTools > console.log.
Common Mistake
Warning
Not using strict equality (===) consistently. The == operator does type coercion: 0 == '' is true, null == undefined is true. Always use === unless you specifically need type coercion (rare).
Practice Task
Note
Bug hunting: (1) Identify the bug in: for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), 100); }. (2) Fix it with let. (3) Explain why it happens (closures + var hoisting).
Quick Quiz
Key Takeaways
- Every JavaScript developer encounters the same bugs.
- == instead of === — '5' == 5 is true (unexpected). Always use ===
- Missing return — Function returns undefined if you forget return
- Mutating vs creating — sort() mutates original. Use [...arr].sort() for safety