In JavaScript, an IIFE (Immediately Invoked Function Expression) is a function that runs immediately after it is defined. Unlike regular functions that must be called separately, an IIFE executes automatically as soon as the JavaScript engine reads it.
IIFEs are commonly used to create a private scope for variables and prevent them from polluting the global scope. This technique is very useful in large applications where multiple scripts are running on the same page.
What is an IIFE?
An IIFE is a function expression that is wrapped inside parentheses and executed immediately. The syntax ensures that the function runs right after it is created.
Hello, Student
In this example, the function runs instantly without needing to call it separately.
Syntax of IIFE
The basic structure of an IIFE consists of two parts:
- A function wrapped in parentheses
- Another pair of parentheses that executes the function
The outer parentheses convert the function into an expression, and the final parentheses trigger its execution.
IIFE with Parameters
An IIFE can also accept parameters, allowing values to be passed during execution.
Welcome Rahul
Why IIFE is Used
One of the main purposes of using IIFE is to avoid creating global variables. Variables declared inside an IIFE remain private and cannot be accessed outside the function.
Private Variable
The variable message exists only inside the IIFE and cannot be accessed outside it.
Arrow Function IIFE
With modern JavaScript (ES6), arrow functions can also be used to create IIFEs.
This is an arrow function IIFE
Benefits of Using IIFE
- Prevents global variable pollution
- Creates private scope for variables
- Useful for modular programming
- Helps avoid variable conflicts in large applications
Conclusion
An Immediately Invoked Function Expression (IIFE) is a powerful JavaScript pattern that allows functions to run immediately after being defined. It helps protect variables from the global scope and keeps code organized.
IIFEs were widely used before modern module systems became popular and are still useful for creating isolated execution environments in JavaScript.
In the next tutorial, you will learn about Callbacks in JavaScript, which explain how functions can be passed as arguments and executed inside other functions.

