xxxxxxxxxx
//expression that are immediately invoked and executed as soon as defined.
//this aviod global scope pollution.
//syntax
(function(a,b){
return a + b;
})(10,20);
//You can also use an arrow function in defining an IIFE:
(() => {
//...
})();
xxxxxxxxxx
(function () {
// …
})();
(() => {
// …
})();
(async () => {
// …
})();
xxxxxxxxxx
var result = (function () {
var name = "Barry";
return name;
})();
// Immediately creates the output:
result; // "Barry"
xxxxxxxxxx
//IIFE (Immediately Invoked Function Expression) or self invokation
// function is executed immediately after creation, wrapped inside parenthesis i.e., ()
(function (){
console.log("Hello World");
//rest of code
})();
xxxxxxxxxx
function add(a,b) {
return a + b;
}
Code language: JavaScript (javascript)
We can pass parameters to the IIFE as follows:
xxxxxxxxxx
(function(window, name){
//code here
})(window, name);