Immediately Invoked Function Expressions (IIFE’s)
An IIFE ^ is a way in JavaScript to define a function and immediately call it after it has been parsed. When defining an immediately invoked function declaration you are able to omit a name for function - making it an anonymous function (this is similar to what you may be used to doing when passing a function as an argument to another function).
To achieve writing an anonymous IIFE see the code block example below, it is imperative that the function is wrapped in a pair of parentheses. Otherwise the parser will read the function declaration and the call as two separate things.
(function() {
// do something
var closureBinding = 10;
})();
console.log(closureBinding);
// closureBinding is not defined;
// anonymous IIFE can also be written as:
(function() {
}()); // the function call is now placed inside the enclosing parentheses.
Other than some other small nuance, they aren’t that special in themselves. They can also be named. There power comes in the way they can be used. There is a number of use-cases I see other developers use IIFE.
To immediately call some functionality without having a named function that could be called again - while also not polluting any of the global space with declarations.
Was the crux of the ‘Revealing Module Pattern’ using function scope to encapsulate code that returned a function with access to its outer function scope after returning (commonly referred to as closure). This was before ES6, with the arrival of let/const which allows the creation of a separate scope inside regular blocks. See https://www.jordanbinskin.com/post/2019/10/01/front-end-mastery-amd-vs-commonjs-vs-esmodules/ for more on this pattern and other module solutions.