Immediately Invoked Function Expression

An IIFE (Immediately Invoked Function Expression) in JavaScript is a function that is defined and executed immediately after its creation. It is often used to create a private scope for variables and avoid polluting the global scope.

Here's an example of an IIFE:


(function() {
    // Code inside the IIFE
    var x = 10;
    console.log("Inside IIFE: x =", x);
})();
                    
// x is not accessible outside the IIFE
// console.log("Outside IIFE: x =", x);  // Uncommenting this line will result in an error
                

In the above example:

  • We define an anonymous function using `(function() { ... })`.
  • The function is immediately invoked with `()` right after its definition.
  • The variable `x` is scoped only within the IIFE and is not accessible outside of it.

Another example of an IIFE:


// named IIFE
(function chai() {
    console.log("DB Connected");
})();


// unnamed IIFE
( () => {
    console.log('DB Connected two');
} )();


// IIFE with parameters passed
( (database) => {
    console.log(`DB connected is ${database}`);
} )('MONGODB');
                
Why would I use an IIFE?

An IIFE (Immediately Invoked Function Expression) in JavaScript serves several purposes:

  1. Encapsulation and Scope Isolation:
    • IIFEs create a private scope for variables, preventing them from polluting the global scope.
    • Variables declared inside an IIFE are not accessible outside of it.
    • This helps avoid naming conflicts and unintended interactions with other scripts.
  2. Module Pattern:
    • IIFEs are commonly used to create modules or self-contained components in JavaScript.
    • By encapsulating functionality within an IIFE, you can expose only specific methods or properties to the outside world, keeping the rest private.
  3. Initialization and Setup:
    • IIFEs are useful for executing setup code or initializing variables.
    • For example, setting up event listeners, configuring libraries, or initializing constants.
  4. Avoiding Global Pollution:
    • By wrapping code in an IIFE, you prevent global variables from being created.
    • This is especially important in large applications to maintain code organization and prevent accidental variable collisions.