/

JavaScript Immediately-invoked Function Expressions (IIFE)

JavaScript Immediately-invoked Function Expressions (IIFE)

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:

1
2
3
(function() {
// code goes here
})();

You can also use arrow functions to define IIFEs:

1
2
3
(() => {
// 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:

1
2
3
4
5
6
7
(function() {
// code goes here
}());

(() => {
// code goes here
})();

In rare cases, you may encounter alternative syntax using unary operators to create IIFEs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
-(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:

1
2
3
(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:

1
2
3
;(function() {
// code goes here
})();

This problem is often resolved by using code bundlers like Webpack, which handle concatenation and ensure proper syntax.