Due to dynamic typing, implicit type coercion, and historical API quirks, JavaScript developers frequently encounter common pitfalls. Recognizing these anti-patterns prevents runtime production bugs.
flowchart TD
Pitfalls["Common JS Mistakes"] --> P1["Floating Point Math: 0.1 + 0.2 !== 0.3"]
Pitfalls --> P2["Loose Equality Coercion: '0' == false"]
Pitfalls --> P3["Missing break in switch statements"]
Pitfalls --> P4["This binding loss in callbacks"]
Pitfalls --> P5["Array typeof check: typeof [] === 'object'"]
| Common Mistake | Root Cause | Correct Solution |
|---|---|---|
0.1 + 0.2 === 0.3 (false) |
Binary floating-point precision | Use Math.abs(a - b) < Number.EPSILON or cents. |
typeof [] === "object" |
Historical type classification | Use Array.isArray(arr). |
typeof null === "object" |
Original JS V8 pointer bug | Use val === null. |
| Modifying array while iterating | Array index shifting | Use filter() or iterate backwards. |
| Unintended Global Variable | Missing const/let in sloppy mode |
Enable 'use strict'; or use ESM. |
// Demonstrating common mistakes and their corrected solutions
// Mistake 1: Array Mutating during forEach
console.log("--- Mistake 1: Array Mutation Trap ---");
const numbers = [1, 2, 3, 4, 5];
// Incorrect: mutating array in-place while iterating causes skipped indices!
// Solution: Use filter() to create a clean new array
const evenNumbersOnly = numbers.filter(num => num % 2 === 0);
console.log("Corrected Even Filter:", evenNumbersOnly);
// Mistake 2: Missing Return in Arrow Function with Curly Braces
// Incorrect: () => { id: 1 } returns undefined because {} is parsed as a block!
// Solution: Wrap object in parentheses () => ({ id: 1 })
const getUserCorrect = (id) => ({ id, role: "admin" });
console.log("Correct Arrow Object Return:", getUserCorrect(99));
// Mistake 3: Loose Comparison Confusion
console.log(`Loose check '0' == false: ${'0' == false}`); // true (Confusing!)
console.log(`Strict check '0' === false: ${'0' === false}`);// false (Predictable!)
eslint:recommended) to catch common syntax and logic mistakes automatically.== checks with ===.Array.isArray(): Never rely on typeof for arrays or null checks.Why does [1, 2, 3] + [4, 5, 6] return "1,2,34,5,6" as a string instead of adding arrays?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.