nullishCoalescingOperators
Prefer nullish coalescing operator (??) over logical OR (||) for nullish values.
✅ This rule is included in the tsstylisticandstylisticStrictpresets.
The logical OR operator (||) returns the right operand when the left operand is any falsy value, including 0, "", false, null, and undefined.
The nullish coalescing operator (??) only returns the right operand when the left operand is null or undefined, preserving other falsy values.
When the left operand can only be nullish (not other falsy values like 0, "", or false), using ?? more clearly expresses the intent and avoids accidentally replacing legitimate falsy values.
Examples
Section titled “Examples”let value: string | null = null;const result = value || "default";let value: number | undefined = undefined;const result = value || 0;function getValue(): object | null { return null;}const result = getValue() || {};let value: string | null = null;const result = value ?? "default";let value: number | undefined = undefined;const result = value ?? 0;function getValue(): object | null { return null;}const result = getValue() ?? {};let value: string = "";const result = value || "default";let value: number = 0;const result = value || 1;Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If your codebase intentionally uses || to handle all falsy values uniformly, or if you have a large legacy codebase where migrating to ?? would require extensive changes, you may want to disable this rule.
Some projects also prefer || for its broader falsy checking behavior when the distinction between nullish and other falsy values is not important.