JavaScript Optimizations & Best Practices
25 min read
PerformanceOptimizationBest PracticesV8JITMemoryDOMAsync Patterns
30 JavaScript Optimizations (The Pro Checklist)
Variables & Scope
| # | Optimization | Why |
|---|---|---|
| 1 | Use const by default, let when needed | Communicates intent, enables engine optimizations |
| 2 | Never use var | Function-scoped, hoisted to undefined, causes bugs |
| 3 | Avoid global variables | Pollute namespace, slow lookups, prevent GC |
| 4 | Use Set for uniqueness checks | set.has() is O(1) vs array.indexOf() O(n) |
| 5 | Use literal notation ({}, []) | Faster than new Object(), new Array() |
DOM & Events
| # | Optimization | Why |
|---|---|---|
| 6 | Cache DOM references | Avoid repeated querySelector calls |
| 7 | Use DocumentFragment | Batch DOM updates into one reflow |
| 8 | Use Event Delegation | One listener on parent vs N on children |
| 9 | Debounce input/resize events | Prevent excessive function calls |
| 10 | Use requestAnimationFrame | Sync with browser paint cycle for smooth animations |
Async & Network
| # | Optimization | Why |
|---|---|---|
| 11 | Use Promise.all for parallel fetches | Don't await sequentially for independent requests |
| 12 | Use AbortController | Cancel stale/unnecessary requests |
| 13 | Use Web Workers for CPU-heavy tasks | Keep the main thread responsive |
| 14 | Use async/await over callbacks | Readable, debuggable, proper error handling |
| 15 | Use IntersectionObserver | Efficient lazy loading without scroll listeners |
Memory & Performance
| # | Optimization | Why |
|---|---|---|
| 16 | Avoid eval() | Security risk, kills engine optimizations |
| 17 | De-reference large objects | Set to null to help GC |
| 18 | Avoid closures in loops | Can accidentally trap large data in memory |
| 19 | Use WeakMap for caches | Entries are GC'd when keys are no longer referenced |
| 20 | Keep object shapes consistent | V8 Hidden Classes optimize consistent structures |
Code Quality
| # | Optimization | Why |
|---|---|---|
| 21 | Use Optional Chaining (?.) | Reduces verbose null checks |
| 22 | Use Nullish Coalescing (??) | Only defaults on null/undefined (not 0 or "") |
| 23 | Use static import | Enables tree shaking by bundlers |
| 24 | Keep functions small | Small functions are more likely to be JIT-inlined |
| 25 | Avoid try/catch inside loops | Prevents JIT optimization of the loop |
| 26 | Profile with Chrome DevTools | Don't guess — measure with Performance & Memory tabs |
| 27 | Use for/while for huge arrays | Faster than forEach for 100K+ elements |
| 28 | Pre-allocate array size | Avoids dynamic resizing overhead |
| 29 | Use short-circuit evaluation | &&, || for concise conditional logic |
| 30 | Use JSON.parse sparingly | Synchronous, blocking — use streaming for large JSON |