
What the Heck is an IIFE in JavaScript?
If you've been around JavaScript long enough, you’ve probably seen something like this:
(function () {
console.log("I'm an IIFE!");
})();
It looks weird at first, but it’s doing something cool. Let’s break it down.
What’s an IIFE?
IIFE stands for Immediately Invoked Function Expression. It’s a function that runs as soon as it’s defined.
Why? To create a private scope and avoid polluting the global namespace—especially useful before let
and const
were common.
How Does It Work?
There are two main parts:
1. Function Expression
Wrapping the function in parentheses tells JavaScript: “this is an expression.”
(function () { ... })
2. Immediate Invocation
These final parentheses call the function right away.
();
Put it together:
(function () {
const message = "This runs immediately!";
console.log(message);
})();
Should You Still Use Them?
Modern JavaScript gives us block scoping via let
, const
, and modules, so IIFEs aren’t as necessary as they used to be. But they’re still a great trick to have in your toolbox—especially in scripts or legacy codebases.