cover-img

IIFE: What is It, and When to Use It?

20 January, 2023

7

7

1

IIFE: What is it, and when to use it?

IIFE stands for Immediately Invoked Function Expression. It is a way to execute a function as soon as it is defined.

Here is an example of an IIFE:

(function () {
console.log("Hello, World!");
})();

The function is defined by wrapping it in parentheses, followed by another set of parentheses to execute the function immediately.

IIFEs are often used to create a new scope in JavaScript, which can be useful for declaring variables that should not be global. They can also be used to avoid naming conflicts between different JavaScript modules.

For example, you might use an IIFE like this:

(function () {
// Declare variables that should not be global
let name = "John";
let age = 30;

console.log(`My name is ${name} and I am ${age} years old.`);
})();

In this case, the variable's name and age are only available within the IIFE and are not accessible from the global scope. This can help prevent naming conflicts with other variables or functions that might be defined in your code.

IIFEs are useful in JavaScript for several reasons:

  1. They create a new scope: As mentioned earlier, IIFEs can be used to create a new scope in JavaScript. This can be useful for declaring variables that should not be global and avoiding naming conflicts between different JavaScript modules.
  2. They execute immediately: Since the function is executed immediately after it is defined, you can use an IIFE to execute code as soon as the page loads or when a particular event occurs.
  3. They are self-contained: Since the function is defined and executed within the same block of code, you can use an IIFE to create self-contained units of code that do not pollute the global scope. This can make your code easier to understand and maintain.
  4. They can be used to prevent global variables: In the past, it was common to use global variables in JavaScript to share data between different parts of a web page. However, global variables can cause problems if multiple scripts or libraries use the same variable names. By using IIFEs, you can avoid global variables and reduce the risk of naming conflicts.

7

7

1

ShowwcaseHQ
Showwcase is where developers hang out and find new opportunities together as a community

More Articles