An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don’t pollute the global object, and they are a simple way to isolate variables declarations
An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created.
IIFEs are very useful because they don’t pollute the global object, and they are a simple way to isolate variables declarations.
This is the syntax that defines an IIFE:
(function() {
/* */
})()
IIFEs can be defined with arrow functions as well:
(() => {
/* */
})()
We basically have a function defined inside parentheses, and then we append ()
to execute that function: (/* function */)()
.
Those wrapping parentheses are actually what make our function, internally, be considered an expression. Otherwise, the function declaration would be invalid, because we didn’t specify any name:
Function declarations want a name, while function expressions do not require it.
You could also put the invoking parentheses inside the expression parentheses, there is no difference, just a styling preference:
(function() {
/* */
}())
(() => {
/* */
}())
#javascript #programming #web-development #developer