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.

An Immediately Invoked Function Expression (IIFE) is a function expression that is defined and executed simultaneously. It leverages lexical scoping to create an isolated execution context, evaluating the function logic immediately during the runtime execution phase when the statement is reached, without requiring a separate invocation call. In TypeScript, an IIFE behaves identically to its JavaScript counterpart but strictly enforces static typing for parameters, return types, and internal variables.

Syntax Mechanics

An IIFE consists of two primary syntactic components:
  1. The Grouping Operator (...): Provides an expression context for the function keyword and its body, ensuring the compiler parses the entire construct as a function expression rather than a function declaration.
  2. The Invocation Operator (...): Appended immediately after the grouping operator to execute the evaluated expression synchronously.

Standard Function Expression IIFE

You can explicitly type the parameters and the return type of the anonymous function.
(function (identifier: string, count: number): void {
    const internalState: boolean = true;
    console.log(`Executing ${identifier}: ${count}`);
})("Process", 42);

Arrow Function IIFE

The arrow function syntax provides a more concise lexical structure. The type annotations follow standard TypeScript arrow function semantics.
const computedValue: number = ((base: number): number => {
    const multiplier: number = 10;
    return base * multiplier;
})(5);

Asynchronous IIFE

When utilizing async/await within an IIFE, the function expression must be marked as async, and the return type must be typed as a Promise.
(async (endpoint: string): Promise<void> => {
    const response: Response = await fetch(endpoint);
    const data: unknown = await response.json();
    console.log(data);
})("https://api.example.com/data");

Generic IIFE

TypeScript allows IIFEs to accept generic type parameters. The generic type is declared before the parameter list and instantiated at the invocation operator.
const genericResult = (<T>(payload: T): T => {
    // Internal logic utilizing type T
    return payload;
})<string>("Strictly typed payload");

Semicolon Prefixing

When an IIFE follows another statement in a file, it is a standard syntactic practice to prefix the grouping operator with a semicolon. This prevents the TypeScript compiler from incorrectly interpreting the IIFE’s grouping operator as a function call on the preceding line’s evaluated result.
const previousStatement = 100

;((): void => {
    const isolatedVar: number = previousStatement * 2;
})()
Master TypeScript with Deep Grasping Methodology!Learn More