JavaScript Immediately Invoked Function Expression (IIFE)
Subject: JavaScript
An Immediately Invoked Function Expression (IIFE) in JavaScript is a function that runs as soon as it is defined. It's mainly used to avoid polluting the global scope and to create private scopes for variables.
What is an IIFE?
- An IIFE is both defined and executed immediately.
- It's wrapped in parentheses to treat it as an expression, followed by
()to invoke it.
Syntax
Or using ES6 arrow function syntax:
Example 1: Simple IIFE
Output:
Example 2: IIFE with Parameters
Example 3: IIFE with Return Value
Why Use IIFE?
1. Avoid Global Scope Pollution
2. Create Private Variables
IIFE vs Regular Function
| Feature | IIFE | Regular Function |
|---|---|---|
| Execution | Immediately | On call |
| Scope Isolation | Yes | No, unless inside a block |
| Reusability | No | Yes |
| Used For | One-time setup, private logic | Reusable tasks |
Key Takeaways
- An IIFE is a function that runs immediately after it's defined.
- It helps encapsulate variables and logic in a private scope.
- Commonly used in older code to prevent global scope pollution.
- Modern alternatives include ES6 modules and
let/constfor block scoping.