domains / app-frameworks / discourse/discourse
Use modern null handling
Leverage modern JavaScript operators and patterns for cleaner, more robust null and undefined handling. This improves code readability and reduces boilerplate while maintaining safety.
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:
- Nullish coalescing (
??) for default values when you specifically want to handlenullandundefined:// Instead of return this.args.onChange ? this.args.onChange : () => {}; // Use return this.args.onChange ?? (() => {}); - Nullish coalescing assignment (
??=) for lazy initialization:// Instead of if (!this.#pendingCleanup[phase]) { this.#pendingCleanup[phase] = []; } // Use this.#pendingCleanup[phase] ??= []; - Logical OR assignment (
||=) for falsy value defaults:// Instead of value = value || ""; // Use value ||= ""; - Leverage truthy/falsy behavior to simplify boolean checks: ```javascript // Instead of return d.hours() !== 0 || d.minutes() !== 0 || d.seconds() !== 0; // Use return d.hours() || d.minutes() || d.seconds();
// 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.