IIFE
April 27, 2023
An IIFE stands for Immediately Invoked Function Expression. It is a JavaScript design pattern that is used to achieve encapsulation and avoid variable collisions in the global scope.
An IIFE is a function that is declared and invoked immediately. It is an anonymous function that is enclosed in parentheses and followed by another set of parentheses, which invoke the function. It looks like this:
(function(){
//code here
})();
The outer set of parentheses makes the function an expression rather than a declaration, and the inner set of parentheses invokes the function immediately after it is defined.
The purpose of an IIFE is to create a new scope for the function, so that any variables declared within it do not pollute the global scope. This is particularly useful when working with complex scripts or libraries, where variable collisions can cause unexpected behavior.
An IIFE can also be used to create private variables and functions. Because the variables and functions declared within the IIFE are not accessible outside of it, they remain private and cannot be modified or accessed by other code. This can be useful for creating modular code that is easy to maintain and update.
Here is an example of how an IIFE can be used to create private variables and functions:
var myModule = (function() {
var privateVar = "I am a private variable";
function privateFunction() {
console.log("I am a private function");
}
return {
publicFunction: function() {
console.log("I am a public function");
}
}
})();
In this example, the myModule
variable is assigned the result of an IIFE that creates a private variable privateVar
and a private function privateFunction
. The IIFE then returns an object that contains a public function publicFunction
, which can be accessed outside of the module.
The private variables and functions can only be accessed within the module, but the public function can be accessed outside of it. This allows the module to maintain encapsulation while still providing a public interface for other code to interact with.
An IIFE can also be used to pass in dependencies to a module. This is known as the Dependency Injection pattern. Here is an example of how this can be done:
var myModule = (function($){
function privateFunction() {
console.log("jQuery version: " + $.fn.jquery);
}
return {
publicFunction: function() {
privateFunction();
}
}
})(jQuery);
In this example, the $
symbol is passed in as a dependency to the module. The IIFE then uses the $
symbol to access the jQuery library within the module. This allows the module to use jQuery without having to rely on it being available in the global scope.
Overall, an IIFE is a powerful tool that can be used to achieve encapsulation, avoid variable collisions, create private variables and functions, and pass in dependencies to a module. It is a commonly used design pattern in JavaScript programming, and can help make your code more modular, maintainable, and scalable.