Immediately Invoked Function Expressions (IIFE)
suggest changeAn immediately invoked function expression (IIFE) is a function expression that is called in the same place it is written. The trailing parentheses do the calling. The function is not hoisted, and its local bindings stay inside it. A name on the function expression is visible only inside that function, which is enough for recursion and for a useful stack frame. alert below is browser-only.
(function() {
alert("I've run - but can't be run again because I'm immediately invoked at runtime, leaving behind only the result I generate");
}());
This is another way to write IIFE. Notice that the closing parenthesis before the semicolon was moved and placed right after the closing curly bracket:
(function() {
alert("This is IIFE too.");
})();
You can easily pass parameters into an IIFE:
(function(message) {
alert(message);
}("Hello World!"));
Additionally, you can return values to the surrounding scope:
const example = (function() {
return 42;
}());
console.log(example); // => 42
A name is optional. It can be used for recursion, and it shows up in the stack trace.
(function namedIIFE() {
throw new Error("failed"); // the stack trace names namedIIFE
}());
Parentheses are the usual way to force a function expression. Where an expression is already expected, the extra wrapping is unnecessary:
const a = function() { return 42 }();
console.log(a) // => 42
Arrow version of immediately invoked function:
(() => console.log("Hello!"))(); // => Hello!