Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ?? (nullish coalescing) operator is a logical operator that evaluates and returns its right-hand operand strictly when its left-hand operand is null or undefined (collectively termed “nullish”). If the left-hand operand is any other value, the operator returns the left-hand operand.
const result = leftExpression ?? rightExpression;

Nullish vs. Falsy Evaluation

The primary mechanical distinction of ?? is its strict adherence to nullish values, contrasting with the logical OR (||) operator, which triggers on any falsy value (e.g., 0, "", NaN, false). The ?? operator preserves valid falsy primitives that would otherwise be overridden by ||.
// ?? evaluates strictly for null or undefined
const val1 = null ?? "fallback";      // "fallback"
const val2 = undefined ?? "fallback"; // "fallback"

// ?? preserves non-nullish falsy values
const val3 = 0 ?? 42;                 // 0
const val4 = "" ?? "default";         // ""
const val5 = false ?? true;           // false

// || overrides all falsy values
const val6 = 0 || 42;                 // 42
const val7 = "" || "default";         // "default"

Short-Circuit Evaluation

The ?? operator implements short-circuiting. The right-hand expression is only evaluated if the left-hand operand resolves to null or undefined. If the left-hand operand is non-nullish, the right-hand execution is entirely bypassed.
function computeHeavyOperation(): number {
    // Execution logic
    return 100;
}

const existingValue = 50;
// computeHeavyOperation() is never invoked because existingValue is not nullish
const finalValue = existingValue ?? computeHeavyOperation(); 

Operator Precedence and Chaining

The ?? operator has a lower precedence than || and &&. To prevent ambiguous evaluation logic, TypeScript and modern JavaScript engines throw a SyntaxError if ?? is chained directly with && or || without explicit grouping.
declare const a: boolean | null;
declare const b: boolean;
declare const c: boolean;

// ❌ SyntaxError: Cannot use unparenthesized '??' within '||' and '&&' expressions.
const invalid = a || b ?? c;
const invalid2 = a && b ?? c;

// ✅ Valid: Explicit precedence via parentheses
const valid1 = (a || b) ?? c;
const valid2 = a || (b ?? c);

Type Narrowing

In TypeScript’s type system, the ?? operator automatically narrows the inferred type of the resulting expression by excluding null and undefined from the left operand’s type union, provided the right operand does not also include them.
declare const input: string | null | undefined;

// TypeScript infers 'result' as type 'string'
// It strips null/undefined from 'input' and unions it with the type of "default"
const result = input ?? "default"; 
Master TypeScript with Deep Grasping Methodology!Learn More