Junior
What is IIFE (Immediately Invoked Function Expression)?
sobes.tech AI
Answer from AI
IIFE — is a function that is declared and immediately executed.
(function() {
// Function code
})();
- Declaration and invocation: Immediately after the declaration (inside parentheses), there is an operator
(), which calls this function. - Creating a private scope: Variables and functions declared inside the IIFE do not pollute the global scope.
- Code isolation: Allows avoiding name conflicts when using multiple JavaScript libraries or scripts.
- Solving closure issues in loops: Helps "capture" the correct value of a variable in each iteration.
// Example of using to create a private scope
(function() {
var privateVar = "PrivateD";
console.log(privateVar); // Will output "Private"
})();
// console.log(privateVar); // Error: privateVar is not defined