Leverage modern JavaScript operators and patterns for cleaner, more robust null and undefined handling. This improves code readability and reduces boilerplate while maintaining safety.
Key patterns to adopt:
??
) for default values when you specifically want to handle null
and undefined
:
// Instead of
return this.args.onChange ? this.args.onChange : () => {};
// Use
return this.args.onChange ?? (() => {});
??=
) for lazy initialization:
// Instead of
if (!this.#pendingCleanup[phase]) {
this.#pendingCleanup[phase] = [];
}
// Use
this.#pendingCleanup[phase] ??= [];
||=
) for falsy value defaults:
// Instead of
value = value || "";
// Use
value ||= "";
// Instead of .filter((e) => e) // Use .filter(Boolean)
5. **Avoid redundant null checks** when functions handle undefined gracefully:
```javascript
// Instead of
if (this.handleBlurTimer) {
cancel(this.handleBlurTimer);
}
// Use (since cancel handles undefined)
cancel(this.handleBlurTimer);
These patterns reduce code verbosity while maintaining or improving null safety, and they clearly express intent about how null/undefined values should be handled.
Enter the URL of a public GitHub repository