https://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function

JavaScript syntax 101. Here is a function declaration:

function foo() {}

Note that there's no semicolon: this is just a function declaration. You would need an invocation, foo(), to actually run the function.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

The ! alone doesn't invoke the function, of course, but we can now put () at the end: !function foo() {}() which has higher precedence than ! and instantly calls the function.

So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:

(function(){})();

Lastly, ! makes the expression return true. This is because by default all immediately invoked function expressions (IIFE) return undefined, which leaves us with !undefined which is true. Not particularly useful.

 
 

https://stackoverflow.com/questions/9267289/what-does-function-in-javascript-mean

Self-Executing Anonymous Function - MDN Web Docs Glossary: Definitions of Web-related terms | MDN https://developer.mozilla.org/en-US/docs/Glossary/Self-Executing_Anonymous_Function

https://developer.mozilla.org/en-US/docs/Glossary/IIFE

IIFE(立即调用函数表达式)

IIFE( 立即调用函数表达式)是一个在定义时就会立即执行的  JavaScript 函数

(function () {
    statements
})();
Copy to Clipboard

这是一个被称为 自执行匿名函数 的设计模式,主要包含两部分。第一部分是包围在 圆括号运算符 () 里的一个匿名函数,这个匿名函数拥有独立的词法作用域。这不仅避免了外界访问此 IIFE 中的变量,而且又不会污染全局作用域。

第二部分再一次使用 () 创建了一个立即执行函数表达式,JavaScript 引擎到此将直接执行函数。

示例

当函数变成立即执行的函数表达式时,表达式中的变量不能从外部访问。

(function () {
    var name = "Barry";
})();
// 无法从外部访问变量 name
name // 抛出错误:"Uncaught ReferenceError: name is not defined"

将 IIFE 分配给一个变量,不是存储 IIFE 本身,而是存储 IIFE 执行后返回的结果。

var result = (function () {
    var name = "Barry";
    return name;
})();
// IIFE 执行后返回的结果:
result; // "Barry"

 

 

IIFE

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.

(function () {
  statements
})();
Copy to Clipboard

It is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts:

  1. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
  2. The second part creates the immediately invoked function expression () through which the JavaScript engine will directly interpret the function.

Use cases

 

Avoid polluting the global namespace

Because our application could include many functions and global variables from different source files, it's important to limit the number of global variables. If we have some initiation code that we don't need to use again, we could use the IIFE pattern. As we will not reuse the code again, using IIFE in this case is better than using a function declaration or a function expression.

(function () {
  // some initiation code
  let firstVariable;
  let secondVariable;
})();

// firstVariable and secondVariable will be discarded after the function is executed.
Copy to Clipboard

The module pattern

We would also use IIFE to create private and public variables and methods. For a more sophisticated use of the module pattern and other use of IIFE, you could see the book Learning JavaScript Design Patterns by Addy Osmani.

const makeWithdraw = balance => (function(copyBalance) {
  let balance = copyBalance; // This variable is private
  let doBadThings = function() {
    console.log("I will do bad things with your money");
  };
  doBadThings();
  return {
    withdraw: function(amount) {
      if (balance >= amount) {
        balance -= amount;
        return balance;
      } else {
        return "Insufficient money";
      }
    },
  }
})(balance);

const firstAccount = makeWithdraw(100); // "I will do bad things with your money"
console.log(firstAccount.balance); // undefined
console.log(firstAccount.withdraw(20)); // 80
console.log(firstAccount.withdraw(30)); // 50
console.log(firstAccount.doBadThings); // undefined, this method is private
const secondAccount = makeWithdraw(20); // "I will do bad things with your money"
secondAccount.withdraw(30); // "Insufficient money"
secondAccount.withdraw(20);  // 0
Copy to Clipboard

For loop with var before ES6

We could see the following use of IIFE in some old code, before the introduction of the statements let and const in ES6 and the block scope. With the statement var, we have only function scopes and the global scope. Suppose we want to create 2 buttons with the texts Button 0 and Button 1 and we click them, we would like them to alert 0 and 1. The following code doesn't work:

for (var i = 0; i < 2; i++) {
  const button = document.createElement("button");
  button.innerText = "Button " + i;
  button.onclick = function () {
    alert(i);
  };
  document.body.appendChild(button);
}
console.log(i); // 2
Copy to Clipboard

When clicked, both Button 0 and Button 1 alert 2 because i is global, with the last value 2. To fix this problem before ES6, we could use the IIFE pattern:

for (var i = 0; i < 2; i++) {
  const button = document.createElement("button");
  button.innerText = "Button " + i;
  button.onclick = (function (copyOfI) {
    return function() {alert(copyOfI);};
  })(i);
  document.body.appendChild(button);
}
console.log(i); // 2
Copy to Clipboard

When clicked, Buttons 0 and 1 alert 0 and 1. The variable i is globally defined. Using the statement let, we could simply do:

for (let i = 0;
i < 2; i++) { const button = document.createElement("button"); button.innerText = "Button " + i; button.onclick = function () { alert(i); }; document.body.appendChild(button); } console.log(i); // Uncaught ReferenceError: i is not defined.
Copy to Clipboard

When clicked, these buttons alert 0 and 1.

 

Self–invoking function in JavaScript? https://www.tutorialspoint.com/self-invoking-function-in-javascript

 

The self-invoking function in JavaScript are known as Immediately Invoked Function Expressions (IIFE). Immediately Invoked Function Expressions (IIFE) is a JavaScript function that executes immediately after it has been defined so there is no need to manually invoke IIFE.

Following is the code for self-invoking function (IIFE) in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="javascript:void(0);en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Immediately Invoked Function Expressions (IIFE)</h1>
<div class="sample"></div>
<script>
   let sampleEle = document.querySelector(".sample");
   (function () {
      sampleEle.innerHTML = "This code is invoked immediately as soon as it is defined";
   })();
</script>
</body>
</html>

Output

The above code will produce the following output −