Immediately-Invoked Function Expression (IIFE)
I have been tinkering with JS module bundling at Netflix and found IIFEs are a recurring pattern in JS Modules. IIFEs, pronounced as iffy, stands for Immediately-Invoked Function Expression.
Table of Content
What exactly is an IIFE
An Immediately-invoked Function Expression (IIFE) is a way to execute functions immediately, as soon as they are created. Let’s see how they are created.
We use empty parenthesis.
A Function is defined inside the parenthesis.
And then we append
() to invoke that function.
The wrapping parentheses around the function definition is needed.
It tells the parser to treat the function definition as an expression.
() just invokes this expression.
🎉 Congratulations 🎉!
You just created an IIFE!
Why do we need IIFE
In simple words:
IIFE allows us to define an isolated scope and execute code in this scope
Can IIFEs return something?
The answer is - Yes, IIFEs can return objects, functions… anything.
Let’s take a look at this code.
We can create an anonymous function expression that gets invoked immediately,
and assign its return value to a variable
Let us try and
return an object from this function.
This code returns an object with properties, these properties are
counter object can then be used to
increment the value of
What is interesting is that you cannot access
It will be
i is not a property of the returned object.
Also, if you try accessing
i you will get a
ReferenceError: i is not defined because
i exists inside the closure of the anonymous function.
I hope with this simple example it is easy to see how IIFE can be used to
- return an object and expose just the public methods
- create private variables (like
iin this case)
The Module Pattern
A Module is a re-usable, self contained collection of code that
- exposes distinct functionalities, that its consumers can use
- never exposes private information
counter created in the code example above is a perfect example of a Module
counter IIFE above
- returns an object with public methods (
- and, is capable of hiding the implementation detail (in this case, the variable
This mechanism to build Modules where we namespace related methods to minimized global-scope variable name pollution and also create private variables is called
The Module Pattern.
This is how IIFE’s can be used to create Modules.
This pattern is commonly used by module bundlers like webpack, browserify, etc when they generate the final bundle.
Thank you for reading this post and I hope this was helpful.