IIFE in JS


IIFE stands for “Immediately Invoked Function Expression” in JavaScript. It is a design pattern where a function is defined and executed immediately after its creation. This pattern is often used to create a private scope for variables, preventing them from polluting the global scope.

Here’s a basic example of an IIFE:

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

In this example, an anonymous function is defined within parentheses, and then another set of parentheses immediately follows, invoking the function. The function is executed as soon as the interpreter encounters it.

One of the main reasons to use IIFE is to encapsulate variables and avoid polluting the global scope. For example:

(function() {
  var localVar = "IIFE example";
  console.log(localVar);
})();
// localVar is not accessible here and does not pollute the global scope

IIFE is also commonly used for creating modules and managing variable scope in more complex JavaScript applications. It helps to prevent naming conflicts and provides a way to organize code in a modular fashion.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *