Week 10: Diving Deeper into Functions
Explore advanced function concepts like callbacks, closures, IIFEs, and the `this` keyword.
Explore Chapter 10Immediately Invoked Function Expressions (IIFE).
An Immediately Invoked Function Expression (IIFE), pronounced "iffy", is a function that is defined and executed immediately after its creation.
Syntax
The key is wrapping the function expression in parentheses () and then immediately calling it with another pair of parentheses ().
(function() {
// Code inside the IIFE
let message = "This runs immediately!";
console.log(message);
// Variables defined here are local to the IIFE's scope
})(); // The final () invokes the function right away
// Can also pass arguments
(function(name) {
console.log("Hello, " + name + " from an IIFE!");
})("IIFE User");
Why Use IIFEs?
- Avoiding Global Scope Pollution: Variables declared inside an IIFE are local to that function's scope. This prevents them from accidentally interfering with variables in the global scope or other parts of your code. This was especially important before the introduction of block scope with let and const.
- Creating Private Scope: Useful for creating modules or plugins where you want to encapsulate internal details.
- Initialization Tasks: Running setup code immediately without creating global variables.
While modern features like block scope and modules have reduced the *need* for IIFEs for simple scope management, they are still a pattern you might encounter in older codebases or use for specific initialization scenarios.