1.9 KiB
1.9 KiB
JavaScript Patterns and Traps
Type Coercion
==vs===— Always use===;"0" == falseis true,"0" === falseis falsetypeof null— Returns"object"(bug from JS v1); check with=== nullNaN !== NaN— UseNumber.isNaN()not=== NaN- Array in boolean context — Empty array
[]is truthy; check.lengthfor emptiness
Async
forEachdoesn't await — Usefor...ofloop orPromise.all(arr.map(async...))for parallel- Unhandled rejection — Always
.catch()or wrap in try/catch; uncaught rejections crash Node asyncfunction returns Promise — Even if you return a value, caller gets a Promise- Race conditions — Multiple
setStatecalls can overwrite; use functional updates or refs
DOM
querySelectorreturns null — Check before accessing properties;document.querySelector('.x').classListcrashes if.xmissing- Event delegation — Add listener to parent, check
e.target; better than listeners on each child innerHTMLsecurity — Never insert user content withinnerHTML; usetextContentor sanitize- Live vs static NodeLists —
getElementsByClassNameis live (updates);querySelectorAllis static
Objects/Arrays
- Shallow copy —
{...obj}and[...arr]are shallow; nested objects share references - Array holes —
Array(5)creates holes;.map()skips them; useArray(5).fill()instead deleteon array — Creates hole, doesn't shift; use.splice()to remove elements- Object key order — Guaranteed insertion order for string keys; numeric keys sort ascending
Functions
thisin arrow functions — Lexically bound; can't be changed with.bind(),.call(),.apply()- Default parameters evaluate —
fn(x = Date.now())evaluates on each call, not definition - Rest parameters must be last —
fn(...rest, other)is syntax error