What is IIFE in JavaScript: Explanation and Example
IIFE (Immediately Invoked Function Expression) in JavaScript is a function that runs right after it is defined. It helps create a private scope to avoid polluting the global space by wrapping code inside a function that executes immediately.How It Works
Think of an IIFE like a self-starting machine. You write a function, then immediately turn it on without waiting or calling it later. This function runs once and creates its own private space where variables and code live without affecting the outside world.
This is useful because JavaScript normally shares variables globally, which can cause conflicts. The IIFE wraps code inside parentheses to treat it as an expression, then adds parentheses at the end to run it right away. It's like wrapping a gift and opening it immediately to use what's inside without leaving a mess outside.
Example
This example shows an IIFE that prints a message immediately and keeps its variable hidden from the outside.
(function() { const message = 'Hello from IIFE!'; console.log(message); })();
When to Use
Use an IIFE when you want to run code once without leaving variables or functions in the global space. It is helpful for:
- Creating private variables that won’t clash with others.
- Running setup code immediately when a script loads.
- Keeping your code clean and avoiding accidental overwrites.
For example, when loading a script on a webpage, an IIFE can initialize settings without exposing internal details to other scripts.
Key Points
- An IIFE runs immediately after it is defined.
- It creates a private scope to protect variables.
- It helps avoid polluting the global namespace.
- Commonly used for initialization and modular code.