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 logical OR (||) operator evaluates operands from left to right and returns the first truthy operand it encounters. If all operands evaluate to falsy values, it returns the value of the last operand. It utilizes short-circuit evaluation, meaning the runtime bypasses the evaluation of subsequent operands immediately after a truthy value is resolved.
expr1 || expr2

Evaluation Mechanics

The operator relies on JavaScript’s underlying boolean coercion rules. The following values are strictly evaluated as falsy: false, 0, -0, 0n, "" (empty string), null, undefined, and NaN. All other values are evaluated as truthy.
  1. If expr1 can be coerced to true (truthy), the expression returns expr1. expr2 is never evaluated.
  2. If expr1 can be coerced to false (falsy), the expression evaluates and returns expr2.

TypeScript Type Resolution

At compile time, TypeScript infers the return type of a || expression as a union of the types of its operands.
declare const leftOperand: string;
declare const rightOperand: number;

// Inferred type: string | number
const result = leftOperand || rightOperand; 

Control Flow Analysis and Type Narrowing

TypeScript’s compiler uses the || operator to perform control flow analysis and type narrowing. When the || operator is evaluated, TypeScript automatically removes types known to be falsy (such as null or undefined) from the resulting type union, provided the right-hand operand does not also contain those types.
declare const maybeString: string | null | undefined;
declare const definiteString: string;

// Inferred type: string
// TypeScript removes 'null' and 'undefined' from the union 
// because they are falsy and force the evaluation of definiteString.
const resolved = maybeString || definiteString;
If the left operand contains literal types that are falsy (e.g., "" or 0), TypeScript will also exclude those specific literal types from the left side of the resulting union.
declare const count: 0 | 1 | 2;
declare const fallback: 100;

// Inferred type: 1 | 2 | 100
// The literal '0' is falsy, so it is stripped from the left operand's contribution.
const finalCount = count || fallback;

Operator Chaining

Multiple || operators can be chained sequentially. The short-circuit evaluation remains strictly left-to-right, and the TypeScript compiler expands the union type to include all potential return values across the chain.
expr1 || expr2 || expr3
declare const a: boolean | undefined;
declare const b: string | null;
declare const c: number;

// Inferred type: true | string | number
// 'false', 'undefined', and 'null' are stripped during left-to-right narrowing.
const chainedResult = a || b || c;
Master TypeScript with Deep Grasping Methodology!Learn More