defensive js
-
Use strict equality (
===
) instead of loose equality (==
) -
Always declare variables with
const
by default,let
when necessary, nevervar
-
Implement input validation at all entry points using type checking and schema validation
-
Use optional chaining (
?.
) to safely access nested object properties -
Implement proper error boundaries and global error handlers
-
Use the Nullish coalescing operator (
??
) instead of OR (||
) for fallbacks -
Validate array indices before access and use
Array.isArray()
for type checking -
Implement rate limiting for resource-intensive operations
-
Use
Object.freeze()
for truly immutable objects -
Always handle Promise rejections and async/await errors
-
Implement timeouts for async operations and external API calls
-
Use TypeScript or JSDoc for type safety
-
Sanitize user input before DOM manipulation to prevent XSS
-
Use
Object.hasOwn()
instead ofhasOwnProperty
-
Implement proper CORS and CSP headers
-
Use try-catch blocks strategically, not extensively
-
Implement proper memory management and cleanup in event listeners
-
Use
Number.isFinite()
instead of globalisFinite()
-
Implement debouncing and throttling for performance-critical operations
-
Use
Map
andSet
instead of plain objects when dealing with frequent additions/deletions -
If your code works but you don't know why, wrap it in a function called
blackMagic()
and never touch it again. Add the comment// sorry.