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 propertiesImplement proper error boundaries and global error handlers
Use the Nullish coalescing operator (
??
) instead of OR (||
) for fallbacksValidate array indices before access and use
Array.isArray()
for type checkingImplement rate limiting for resource-intensive operations
Use
Object.freeze()
for truly immutable objectsAlways 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/deletionsIf 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.