How to avoid common JavaScript pitfalls and bugs
· Category: JavaScript
Short answer
Common pitfalls include relying on implicit coercion, mutating shared state, misunderstanding this, and creating closure loops with var.
Steps
- Always use strict equality:
javascript if (x === 5) { /* ... */ } - Declare variables with
letorconst:javascript for (let i = 0; i < 3; i++) { /* ... */ } - Avoid mutating arguments:
javascript function update(obj) { return { ...obj, active: true }; } - Bind or use arrow functions to preserve
this. - Await all Promises before using their values.
Tips
- Use a linter like ESLint with strict rules.
- Write unit tests for edge cases involving null, undefined, and empty collections.
Common issues
typeof null === "object"is a legacy bug; use=== nullinstead.NaNis not equal to itself; useNumber.isNaN().- Modifying an array while iterating over it skips elements.