What is an immediately invoked function expression, and why would you write one?
An immediately invoked function expression is a function that you define and call on the same line. The function is created as a value rather than as a declaration, and the parentheses after it call it straight away.
(function () {
const secret = 'hidden';
console.log(typeof secret); // 'string'
})();
// The same idea with an arrow function:
(() => {
console.log('arrow IIFE');
})();
// Arguments are passed in the call:
(function (a, b) {
console.log(a + b);
})(2, 3);Historically the pattern had one main job, which was creating a private scope. Before block scoping existed, the only way to get a scope that nothing outside could touch was to define a function and call it immediately. Everything declared inside was unreachable from the outside world, and the whole thing could return a single value if you wanted one. That is where the name immediately invoked function expression comes from, and it is also why the older pattern usually ends with a semicolon and a closing parenthesis. The pattern is an expression statement, and that statement evaluates to the result of the call.
Today the pattern is much less necessary. The let and const declarations are block scoped, so you can get a private scope by putting your code inside a block. An ES module also has its own scope at the top level. What is still useful is the idea of wrapping something that should run exactly once and immediately, such as a small self-contained piece of setup logic, and returning a value from it.
One thing to avoid is using this pattern purely to create a global. Assigning to an undeclared name inside one still creates a global property, so the pattern does not give you any real hiding unless you keep the values inside it.