Immediately-Invoked Function Expressions (IIFE) are functions that will execute when they are created.
(function(){console.log("IIFE");})();// this will print 'IIFE'
We define a function inside parentheses, and add ()
to execute that function.
We can also provide a name to the IIFE function.
(function print(){console.log("IIFE");})();
The function name is optional for function expression, but it is required for the function declaration.
We can move the ()
inside the expression parentheses.
(function(){console.log("IIFE");})();// we can also do like(function(){console.log("IIFE");}());
The IIFE must be enclosed inside the parentheses, otherwise, we will get a SyntaxError
.
function(){
console.log("IIFE");
}()
To avoid these parentheses, we can add any of these operators (~, +, -, !
) before the function keyword.
+function print(){
console.log("IIFE");
}()
-function print(){
console.log("IIFE 1");
}()
When internally adding this operator, JavaScript tries to convert the function to a value, which adds parentheses.
Creating IIFE using arrow function:
(() => {
console.log("IIFE");
})()
Sending params to IIFE:
((a) => {console.log(a); // prints 10})(10)