IIFE (Immediate Invoke Function Expression)

Akshay Waingankar
2 min readOct 18, 2021

Immediate Invoke Function Expression(IIFE) is the function that runs as soon as it is defined.

Let's see how the syntax looks like.

Normal function
(function(){
/* code here*/
})()
Arrow function
(()=>{
/* code here*/
})()
With Semicolon on start
;(()=>{
/* code here*/
})()

In the above IIFE,

  1. we don't need to provide any name to the function and it is written inside round brackets i.e ( ).
  2. When we write a JavaScript function we need to call the function for execution so in this case, last round brackets will act as calling the function i.e ( );
  3. We can pass parameters like
(function(val){
console.log("val: "+val);
})(10);

Advantages

  1. Self execution
  2. Function able to access outside variables
var x = "Outside variable";
(function (){
console.log("x : "+x);
})()
Output
"x : Outside variable"

3. Variables that are declared inside IIFE are function scopes only

(function (){
var x = "Inside variable";
})()
console.log("x : "+x);Error
Uncaught ReferenceError: x is not defined"

Hope this article cleared the IIFE concept.

Happy Coding 👍

Other articles

--

--