Recent Post:
Categories:
An IIFE (Immediately Invoked Function Expression) is a function that is executed immediately after it is defined. It helps create a local scope and avoid polluting the global namespace. IIFEs are often used to encapsulate code and avoid variable collisions.
An IIFE is defined by wrapping the function declaration in parentheses, followed by another pair of parentheses to invoke it.
code
(function() {
console.log("This is an IIFE!");
})();
The function is wrapped in parentheses to convert it into an expression. The () at the end immediately invokes the function.
You can also pass parameters to an IIFE.
code
(function(name) {
console.log("Hello, " + name + "!");
})("Satyendra");
The IIFE takes a parameter name, and the argument "Satyendra" is passed when invoking it.
Encapsulation: IIFEs create a local scope, keeping variables and functions private. Avoiding Global Namespace Pollution: Variables defined inside an IIFE are not accessible from the outside, helping prevent conflict
You might use an IIFE to create a module-like structure.
code
const myModule = (function() {
let privateVariable = "I am private";
return {
getPrivate: function() {
return privateVariable;
}
};
})();
console.log(myModule.getPrivate()); // Output: I am private
console.log(myModule.privateVariable); // Output: undefined
The variable privateVariable is not accessible outside the IIFE, ensuring that it remains private.
The term "self-invoking function" typically refers to the same concept as an IIFE. Both describe a function that runs immediately upon creation.
However, "self-invoking" can also refer to any function that calls itself (recursion). This can create confusion, so it's important to clarify the context.
An IIFE is a function that is executed immediately after its definition, providing a local scope and avoiding global namespace pollution.
It can accept parameters, making it versatile for various applications.
IIFEs are useful for encapsulating code and creating modules.