An Immediately Invoked Function Expression (IIFE) is a JavaScript function that runs as soon as it is defined. It is a design pattern used to create a private scope, ensuring that variables declared inside the function do not "leak" out into the global scope and conflict with other scripts.
The Grouping Operator (): This wraps an anonymous function, turning it from a declaration into an expression.
The Invocation (): This immediately executes the function.
Avoiding Global Scope Pollution: In older versions of JavaScript (before let and const), any variable declared with var inside a script was added to the global window object. IIFEs were the primary way to 'trap' variables so they wouldn't conflict with other scripts.
Creating Private Variables: Because the function creates its own Execution Context, variables defined inside the IIFE cannot be accessed from the outside.
Initialization Logic: If you have code that only needs to run once when the page loads (like setting up event listeners or fetching initial data), an IIFE keeps that setup logic separate from the rest of your app.
With the introduction of ES Modules (import/export) and block-scoping (let/const), the need for IIFEs has decreased, but they are still used in specific scenarios
Top-level await: Wrapping code to use await in environments that don't support it at the top level.
Minification: Minifiers often wrap code in IIFEs to safely rename variables to single letters without breaking global logic.
Module Patterns: In libraries where you want to expose only a specific API while keeping helper functions hidden.