Thursday, November 14, 2024

JavaScript IIFE Immediately Invoked Function Expression

An Immediately Invoked Function Expression (IIFE) in JavaScript is a function that is executed immediately after it’s defined. IIFEs are commonly used to create a private scope, helping avoid polluting the global scope. There are several ways to create an IIFE in JavaScript. Here are the most common approaches:

1. Using Parentheses Around the Function
This is the classic and most common syntax for an IIFE.
(function() {
  console.log("IIFE using parentheses around function");
})();
2. Using Parentheses After the Function
In this style, parentheses are placed immediately after the function expression without wrapping the function itself in parentheses.
(function() {
  console.log("IIFE using parentheses after function");
}());
3. Using an Arrow Function
With ES6, arrow functions can also be used for IIFEs.
(() => {
  console.log("IIFE using arrow function");
})();
4. Using the + Operator Before the Function
You can use operators like +, -, ~, or ! to make JavaScript treat the function as an expression and invoke it immediately.
+function() {
  console.log("IIFE using + operator");
}();
5. Using the ! Operator Before the Function
Similarly, the ! operator can be used to create an IIFE.
!function() {
  console.log("IIFE using ! operator");
}();
6. Using the void Operator
The void operator forces the function to be evaluated as an expression and ignores its return value.
void function() {
  console.log("IIFE using void operator");
}();
7. With an Async Function
You can also create an IIFE with an async function, which can be useful for immediately invoking code that uses await.
(async function() {
  console.log("IIFE with async function");
  // await someAsyncOperation();
})();
8. With an Arrow Async Function
This combines an arrow function with async, useful in modern JavaScript.
(async () => {
  console.log("IIFE with async arrow function");
  // await someAsyncOperation();
})();

Summary

The most commonly used IIFE syntax is:
  • (function() { ... })();
  • (function() { ... }());
  • However, other variations (+, -, !, void) may also be seen, especially in legacy code or when creating a specific effect like ignoring the return value (void).

No comments:

Post a Comment

Hot Topics