The Immediately Invoked Function Expression (IIFE) pattern is a common JavaScript design pattern that involves wrapping a function expression in parentheses and immediately invoking it. The primary purpose of an IIFE is to create a new scope for the function, allowing you to define private variables and functions that are not accessible from the global scope.
Here’s an example of how to create an IIFE in JavaScript:
(function() {
// private variable
const foo = "bar";
// private function
function baz() {
console.log("baz");
}
// public API
window.myModule = {
doSomething() {
console.log(foo);
baz();
}
};
})();
In this example, we define an anonymous function expression and immediately invoke it. Within the function, we define a private variable foo and a private function baz. We then create a public API by adding a property to the window object, which exposes a method doSomething that can access the private variable and function.
One of the main advantages of using an IIFE is that it allows you to avoid polluting the global scope with your variables and functions. This can help prevent naming collisions and other issues that can arise when multiple scripts are loaded on a page.
Another advantage of using an IIFE is that it can be used for encapsulation and modularity. By defining private variables and functions within the function, you can create a module or plugin that can be easily reused and maintained.
In summary, the IIFE pattern is a powerful technique for creating private variables and functions in JavaScript and preventing global namespace pollution. It allows you to create modular and reusable code that is easy to maintain and test.