What is IIFE?
IIFE stands for Immediately Invoked Function Expression. It is a JavaScript function that runs as soon as it is defined. The primary purpose of IIFE is to create a local scope for variables, protecting them from being accessed or modified outside the function.
Syntax of IIFE
(function () {
// your code goes here...
})();
Let's understand this:
Here we have defined a regular funcition
, but instead of naming it and then calling it, we are calling it immediately.
but remember to wrap your function with paranthesis ()
also called Grouping Operator
, they are necessary otherwise javascript parser will detect it as a regular function and throw function declaration
error.
We can also use arrow functions
(()=>{
// your code goes here...
})();
Why do we use IIFE?
The main reason why we use iife
is to avoid polluting global namespace
, you see in large applications we can have multiple global variables plus variables from external sources. We need to limit the numbers of global variables, that's why we use iife
in those cases where a function don't need to be used again.
IIFE is also a design pattern where function execute itself immediately.