An Immediately Invoked Function Expression (IIFE) in JavaScript is a function that is defined and executed immediately after its creation.
🔹 Syntax:
(function() {
// code inside IIFE
console.log("IIFE executed");
})();
✅ Key Characteristics:
- It’s a function expression wrapped in parentheses.
- Immediately invoked by adding
()after the function. - Creates a private scope, avoiding pollution of the global scope.
- Often used in module patterns, especially before
let,const, andimport/exportwere introduced.
✅ Example with Parameters:
(function(name) {
console.log("Hello, " + name);
})("Teekam");
🧠 Why Use IIFE?
- Avoids variable conflicts in global scope.
- Helps in encapsulation.
- Used in older JavaScript to simulate private variables.
📝 In Summary:
An IIFE is a function that runs immediately upon definition, mainly used to create isolated scopes and protect variables from leaking into the global scope.