Immediately Invoked Function Expressions (IIFE) in JavaScript

Immediately Invoked Function Expressions (IIFE) in JavaScript

In JavaScript, sometimes we want to execute a function immediately after defining it. This is where Immediately Invoked Function Expressions (IIFE) come in handy. An IIFE is a function that runs as soon as it is defined. This pattern is particularly useful for reducing the pollution of the global scope and avoiding conflicts with other code.

What is an IIFE?

An IIFE is a function that is executed right after it is created. This can help to encapsulate variables and functions, preventing them from interfering with the global scope.

Here's a basic example of an IIFE:

(function connectingDB(){
    console.log("DB CONNECTED");
})();

In this example, the connectingDB function is defined and immediately invoked. This means that DB CONNECTED will be logged to the console as soon as the script runs. The parentheses () at the end of the function definition invoke it immediately.

Why Use IIFE?

Reducing Global Scope Pollution

In JavaScript, all variables defined at the top level are added to the global scope. This can cause conflicts if different parts of your code define variables with the same name. By using IIFE, we can create a new scope, thus avoiding such conflicts.

Syntax of IIFE

To understand the syntax, think of how you would normally call a function like connectingDB(). Now, replace connectingDB with the actual function definition wrapped inside parentheses:

(function connectingDB(){
    console.log("DB CONNECTED");
})();
//outputs: DB CONNECTED

The function definition is wrapped in parentheses to make it an expression, and the () at the end immediately invokes it.

Using IIFE with Arrow Functions

We can also write IIFE using arrow functions for a more concise syntax. Here is an example:

(() => {
    console.log("DB CONNECTED TWO");
})();

This unnamed IIFE achieves the same result as the previous example, logging DB CONNECTED TWO to the console.

Passing Arguments to IIFE

Sometimes, you might want to pass arguments to an IIFE. This is also possible and can be done as follows:

((name) => {
    console.log(`DB CONNECTED TWO ${name}`);
})("harsh");

In this example, the arrow function takes a parameter name, and when invoked, it logs DB CONNECTED TWO harsh to the console.

Summary

IIFE is a powerful pattern in JavaScript that helps to immediately execute a function and encapsulate its variables and functions to avoid polluting the global scope. This can be particularly useful in larger codebases where global scope conflicts are more likely. Whether using traditional function expressions or modern arrow functions, IIFE is a handy tool to keep in your JavaScript toolbox.