Why create self-invoking functions when it is possible to create a context using curly braces?
sobes.tech AI
Answer from AI
Immediately Invoked Function Expressions (IIFE) are used to create an independent lexical scope, preventing "pollution" of the global scope and avoiding variable name conflicts. Curly braces in regular code blocks (outside functions) in older versions of JavaScript (for example, before ES6 with let and const) did not create such an independent scope for variables declared with var.
Main reasons for using IIFE:
- Scope Isolation: Variables and functions declared inside an IIFE are not accessible outside.
- Privacy: Hiding implementation details and preventing accidental modification of internal data.
- Avoiding conflicts: Especially when integrating multiple libraries or scripts that may use the same variable names.
- Closures: IIFEs are often used to create closures that retain access to variables from the outer scope after the IIFE has executed.
Example of using IIFE to create a private scope:
// IIFE
(function() {
var privateVariable = "I am secret";
function privateFunction() {
console.log(privateVariable);
}
// Access to private elements only inside IIFE
privateFunction();
})();
// Attempting to access outside will cause an error or return undefined (depending on strict mode)
// console.log(privateVariable); // Error
Example of a regular block with var where scope is not isolated:
// Regular code block
{
var publicVariable = "I am accessible outside";
}
console.log(publicVariable); // Will output "I am accessible outside"
With the advent of let and const in ES6, code blocks enclosed in curly braces started to create block scope, reducing the need to use IIFE solely for scope isolation in such cases. However, IIFEs are still useful for creating closures, modularity, and executing code immediately after declaration.
// Block scope with let
{
let privateToBlock = "Visible only here";
console.log(privateToBlock);
}
// console.log(privateToBlock); // Error