In JavaScript, wrapping the entire content of a source file generally comes with immediately invoking it. The function is called an Immediately Invoked Function Expression, or IIFE. It is also called a Self-Executing Anonymous Function.
(function () {
/* โฆ */
})();
It's a design pattern commonly used in the ES6 Module Pattern before ES6 modules were introduced. It helps us encapsulate data and functionality inside a module. jQuery plugins were usually created with IIFEs.
IIFEs are significant because:
- they help with namespacing functions and variables in a library. Namespacing helps us prevent polluting the global namespace.
- they help us control privacy of variables and functions. With an IIFE, we are able to expose only the APIs that we want to -- by returning them in an object, and hide the rest.
References
Top comments (3)
The most useful thing about IIFE is variable minification. Minification tools wonโt touch global variable names so it is impossible to minify global variables.
This is not correct. The introduction of modules in ES6 actually allows us to avoid having to do this to encapsulate our code.
Yes, thanks for pointing out!