An Immediately-invoked Function Expression, also known as an IIFE, is a way to execute functions immediately once they are created. IIFEs offer several benefits, such as not polluting the global object and providing a simple way to isolate variable declarations.
To define an IIFE, you enclose a function inside parentheses and immediately invoke it by appending ()
at the end:
(function() {
// code goes here
})();
You can also use arrow functions to define IIFEs:
(() => {
// code goes here
})();
The wrapping parentheses make the function internally considered an expression, allowing it to be invoked without a function name. Function declarations, on the other hand, require a name. You can also place the invoking parentheses inside the expression parentheses. It’s just a matter of personal preference:
(function() {
// code goes here
}());
(() => {
// code goes here
})();
In rare cases, you may encounter alternative syntax using unary operators to create IIFEs:
-(function() {
// code goes here
})() +
(function() {
// code goes here
})()
~(function() {
// code goes here
})()
!(function() {
// code goes here
})()
Named IIFEs are also possible with regular functions (not arrow functions). The name does not affect the function’s ability to avoid leaking into the global scope, and it cannot be invoked again after its execution:
(function doSomething() {
// code goes here
})();
Using a semicolon to start an IIFE is sometimes seen in code. It helps prevent issues when concatenating JavaScript files, especially if the last line of a file contains statements that could cause a syntax error without the semicolon:
;(function() {
// code goes here
})();
This problem is often resolved by using code bundlers like Webpack, which handle concatenation and ensure proper syntax.