Understanding IIFE (Immediately Invoked Function Expressions) in JavaScript


JavaScript is full of powerful features that help developers write clean, modular, and efficient code. One such feature is the IIFE, or Immediately Invoked Function Expression. If you’ve ever seen a function that seems to run itself right after it’s defined, chances are you were looking at an IIFE.
In this blog post, we’ll break down what IIFEs are, why they exist, and how they can be useful in real-world JavaScript code.
What is an IIFE?
(function () {
console.log("This is an IIFE");
})();
Output:This is an IIFE
Let’s dissect this:
The function is wrapped in parentheses to turn it into a function expression.
Another pair of parentheses at the end
()
immediately invoke the function.
Why Use an IIFE?
1. Avoid Polluting the Global Scope
In JavaScript, variables declared with var
in the global scope become properties of the window
object in browsers. Using an IIFE allows you to create a private scope:
(function () {
var secret = "I am hidden from the global scope";
console.log(secret);
})();
console.log(secret); // ReferenceError: secret is not defined
2. Create Private Variables
IIFEs are useful for data encapsulation—variables declared inside an IIFE can’t be accessed from outside, helping prevent name conflicts.
3. Use Once and Forget
If you have some initialization logic that only needs to run once, you can wrap it in an IIFE.
(function () {
console.log("App initialized");
// setup code here
})();
IIFE Variations
With Parameters:
(function(name) {
console.log(`Hello, ${name}!`);
})("Sam");
Arrow Function IIFE:
(() => {
console.log("Arrow function IIFE");
})();
Real-World Example
Let’s say you're writing a module in plain JavaScript without any build tools or frameworks:
const Counter = (function () {
let count = 0;
return {
increment: function () {
count++;
return count;
},
decrement: function () {
count--;
return count;
},
getCount: function () {
return count;
}
};
})();
console.log(Counter.increment()); // 1
console.log(Counter.increment()); // 2
console.log(Counter.getCount()); // 2
Here, count
is private to the IIFE and can only be accessed or modified using the returned methods.
Conclusion
IIFEs are a neat way to:
Avoid global variable pollution
Create private variables
Execute code immediately
While modern JavaScript (with let
, const
, and modules) has reduced the need for IIFEs in many scenarios, they’re still useful in certain patterns and legacy codebases.
So next time you see a function with funky double parentheses, you'll know: it's not weird—it’s an IIFE doing its job.
Happy coding! If you found this helpful, feel free to share it or drop your questions in the comments.
Subscribe to my newsletter
Read articles from Samridha Dhital directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
