IIFE or Immediately-invoked Function Expressions are functions that we execute immediately after we define them. IIFE was used to isolate the variables and stop polluting the global object. But with the introduction of block scope, modules, let & const statements IIFE is rarely needed.
Immediately invoked Function Expressions
The following is the pattern of the IIFE.
1 2 3 4 5 | (function() { // statements })() |
To create an IIFE, first, create a function. Note that we have not given any name to the function (i.e. functional declaration syntax), not assigned it to some variable (like in function expression)
1 2 3 4 5 | function(a,b) { console.log(a+b) } |
Wrap it inside the bracket.
1 2 3 4 5 6 7 | ( function(a,b) { console.log(a+b) } ) |
Finally, we need to execute it. To do that add parentheses at the end with a value for each parameter inside the parentheses
1 2 3 4 5 6 7 8 9 10 11 | ( function(a,b) { console.log(a+b) } )(1,2); **** Result *** //3 |
Adding the parentheses will invoke the IIFE immediately.
We need to add the trailing semicolon if we use two IIFE one after another. Otherwise code won’t work.
1 2 3 4 5 6 7 8 | (function () { ... }()) // no semicolon (function () { ... }()); |
Named IIFE
You can also give a name to IIFE.
1 2 3 4 5 | (function addNum(a,b) { console.log(a+b) })(1,2); |
But you cannot use that name call the function
1 2 3 | addNum(); //Uncaught ReferenceError: addNum is not defined |
Need for IIFE
IIFE was used to create new JavaScript Scope before the arrival of the let
& const
keyword in ES6 and the block scope
Take a look at the following code. The someVar
variable is declared inside the if condition. But you can access it outside the if condition also.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function someFunc() { cond = true; if (cond) { var someVar = "some Variable"; //More Statements } //someVar can be accessed here console.log(someVar); "some Variable"; } someFunc(); |
Now moving the if condition inside an IIFE creates a new function scope. We now cannot access the variables declared inside the IIFE. Accessing the someVar
results in an error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function someFunc() { cond = true; ( function () { if (cond) { var someVar = "some Variable"; //More Statements } })(); //Uncaught ReferenceError: someVar is not defined console.log(someVar); } someFunc(); |
But since the ES6, we can use the let
(or const
) instead of var
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function someFunc() { cond = true; if (cond) { let someVar = "some Variable"; //More Statements } console.log(someVar); //Uncaught ReferenceError: someVar is not defined } someFunc(); |
Similarly, the following code creates a block scope around curly braces Hence the variable i
is invisible outside the curly braces. Without the let statement only way to achieve this is using the IIFE.
1 2 3 4 5 6 7 8 | { let i=10; //Some Statements } console.log(i); //Uncaught ReferenceError: i is not defined |