📜  js 中的 IFFI - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:59.654000             🧑  作者: Mango

IIFE in JavaScript

IIFE stands for Immediately Invoked Function Expression. As the name suggests, IIFE is an anonymous function that is immediately invoked after it is defined.

IIFE has many use cases, including:

  1. Creating Private Scope
  2. Avoiding Global Namespace Pollution
  3. Initializing Variables
  4. Implementing Modules
  5. Creating Closures
Syntax

The syntax of IIFE is as follows:

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

The function is enclosed in parentheses and called immediately using the () operator. This syntax ensures that the function is executed just once and won't be available in the global scope.

Example

Let's take an example of creating private scope using IIFE.

(function() {
  let count = 0;
  
  function increment() {
    count++;
    console.log(count);
  }
  
  function decrement() {
    count--;
    console.log(count);
  }
  
  increment();
  decrement();
})();

In this example, we have defined a counter that is not available in the global scope. We have two functions, increment and decrement, both of which manipulate the counter. When we invoke the IIFE, it will output the following on the console:

1
0
Conclusion

IIFE is a powerful tool that JavaScript developers use to create private scope, avoid global namespace pollution, and implement modules. It helps in securing the code and avoiding conflicts between multiple libraries.