IIFE (Immediate Invoke Function Expression)
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,
- we don't need to provide any name to the function and it is written inside round brackets i.e ( ).
- 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 ( );
- We can pass parameters like
(function(val){
console.log("val: "+val);
})(10);
Advantages
- Self execution
- 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