What is IIFE (Immediately Invoked Function Expression) in JavaScript?

What is IIFE (Immediately Invoked Function Expression) in JavaScript?

IIFE stands for Immediately Invoked Function Expression. It is a JavaScript function that runs as soon as it is defined. In other words, it is a function that is executed immediately after it is created. The primary purpose of an IIFE is to preserve a private scope within your code.

Why use IIFE?

IIFE is used to avoid polluting the global namespace. When working with JavaScript, it is essential to avoid declaring variables in the global scope. This is because variables declared in the global scope can be accessed and modified by any code, which can lead to unexpected behavior. By using IIFE, you can create a private scope that keeps your variables and functions separate from the global scope.

How to use IIFE?

An IIFE is defined using a function expression. It starts with an opening parenthesis, followed by a function keyword, and then the function body. Finally, it ends with a closing parenthesis, which immediately invokes the function.

Here’s an example:

(function() {
  // code goes here
})();

In the code above, we define an anonymous function and immediately invoke it. The function is wrapped in parentheses to ensure that it is treated as an expression. The final set of parentheses immediately invokes the function.

Passing arguments to IIFE

You can also pass arguments to an IIFE. The arguments are passed in the second set of parentheses.

(function(name) {
  console.log(`Hello, ${name}!`);
})('John');

In the code above, we pass the argument ‘John’ to the IIFE, which is then logged to the console.

Using IIFE with the module pattern

The module pattern is a common design pattern used in JavaScript to create modules with private and public methods and properties. An IIFE is often used in conjunction with the module pattern to create a private scope for the module.

const counter = (function() {
  let count = 0;

  return {
    increment() {
      count++;
    },

    decrement() {
      count--;
    },

    getCount() {
      return count;
    }
  };
})();

console.log(counter.getCount()); // 0
counter.increment();
console.log(counter.getCount()); // 1
counter.decrement();
console.log(counter.getCount()); // 0

In the code above, we define a counter module using the module pattern and IIFE. The count variable is private and cannot be accessed outside the module. The increment, decrement, and getCount methods are public and can be accessed outside the module.

Conclusion

IIFE is a powerful tool in JavaScript that allows you to create private scopes and avoid polluting the global namespace. It is often used in conjunction with the module pattern to create modular code. By using IIFE, you can create more secure and maintainable code.