IIFE stands for Immediately Invoked Function Expression. It’s a common pattern in JavaScript where you define and execute a function all in one go.
Here’s a basic example:
(function() {
// Your code here
})();
This construct creates a function expression enclosed within parentheses (function(){}), and then immediately invokes it with the () at the end.
One of the main reasons for using IIFE is to create a new scope for your code. Variables declared inside the IIFE are not accessible from outside, which helps in preventing polluting the global scope. Additionally, it's often used for modularizing code and avoiding naming conflicts.
// Global scope
var globalVar = "I'm global";
(function() {
// Inside the IIFE, a new scope is created
var localVar = "I'm local";
console.log(globalVar); // Accessible, prints: "I'm global"
})();
console.log(globalVar); // Accessible, prints: "I'm global"
console.log(localVar); // Not accessible, throws a ReferenceError
In this example:
globalVar is accessible both inside and outside the IIFE because it’s declared in the global scope.
localVar is only accessible inside the IIFE. Trying to access it outside the IIFE will result in a ReferenceError because it’s scoped to the function and not visible outside of it.