domains / app-frameworks / 30-seconds/30-seconds-of-code
Consistent Null Handling
Use a consistent null/undefined policy and make it explicit in both type checks and call/return behavior. - **Guard before indexing/access:** when inputs may be missing or null, check the right predicate (e.g., `Array.isArray`) and return a consistent “not found” value (commonly `undefined`).
Use a consistent null/undefined policy and make it explicit in both type checks and call/return behavior.
- Guard before indexing/access: when inputs may be missing or null, check the right predicate (e.g.,
Array.isArray) and return a consistent “not found” value (commonlyundefined).const head = arr => (Array.isArray(arr) && arr.length ? arr[0] : undefined); - Be explicit about
nullin type logic:typeof null === 'object', so include a directvalue === null(and don’t assumeinstanceofcovers null).const isPrimitive = value => !['object', 'function'].includes(typeof value) || value === null; - Avoid
nullsentinels in callback calls when semantics matter: if a callback’s behavior depends on arguments, prefer no arguments (orundefined) rather than passingnull.const next = () => { const fn = fns[curr++]; fn(fn === last ? undefined : next); // or fn() when you want 0 args }; - Prefer default parameters over
=== undefinedconditionals:const take = (arr, n = 1) => arr.slice(0, n);
Apply this consistently across helpers to prevent unexpected undefined results, null reference errors, and subtle argument-count differences.