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 else if clause is a conditional control flow structure used to evaluate a sequence of mutually exclusive boolean expressions. It acts as an intermediary branch within an if...else statement chain, executing its associated block of code strictly when all preceding conditions evaluate to falsy and its own condition evaluates to truthy.

Syntax

The else if clause must immediately follow an if block or another else if block. It requires a parenthesized expression that the JavaScript runtime will implicitly coerce to a boolean.
if (expression1) {
  // Executes if expression1 is truthy
} else if (expression2) {
  // Executes if expression1 is falsy AND expression2 is truthy
} else if (expression3) {
  // Executes if expression1 and expression2 are falsy AND expression3 is truthy
} else {
  // Executes if all preceding expressions are falsy
}

Execution Mechanics

  1. Sequential Evaluation: The JavaScript engine evaluates the chain top-to-bottom.
  2. Short-Circuiting: The evaluation halts as soon as a truthy condition is encountered. Once an else if block executes, all subsequent else if and else blocks in the chain are entirely bypassed without their conditions being evaluated.
  3. Chaining Limit: There is no syntactical limit to the number of else if clauses that can be chained together, though deep chains are often refactored into switch statements or record maps for performance and readability.

TypeScript Control Flow Analysis (Type Narrowing)

In TypeScript, the compiler performs Control Flow Analysis (CFA) across else if chains. When a type guard is used as the condition, TypeScript narrows the type of the variable within that specific block and excludes that type from subsequent else if branches.
function evaluateType(data: string | number | boolean[]) {
  if (typeof data === "string") {
    // TS Compiler: 'data' is strictly 'string'
    data.toUpperCase();
  } else if (typeof data === "number") {
    // TS Compiler: 'data' is strictly 'number'. 
    // The 'string' type was eliminated by the preceding 'if'.
    data.toFixed(2);
  } else if (Array.isArray(data)) {
    // TS Compiler: 'data' is strictly 'boolean[]'.
    // Both 'string' and 'number' types were eliminated.
    data.push(true);
  }
}
If an else if chain exhausts all possible types of a union, TypeScript infers the type in any trailing else block as the never type, which is commonly used for exhaustive checking.
Master TypeScript with Deep Grasping Methodology!Learn More