Typically, we declare a function test) {}, which can be called by Test (). However, if we add () at the end of this function declaration, the parser is incomprehensible.
function Test () { console.log (' Hello world! ' );} (); // The parser is not understandable.
So why wrap the function body part in ()?
(function Test () { console.log (' Hello world! ') // output Hello world!
When the interpreter interprets a statement, it is understood as a function declaration if it starts with the functions. Instead of using parentheses to define the function body, the parser will handle the defined function in the form of a function expression, and adding another () after the function expression becomes a function that executes immediately. in other words, any method that eliminates ambiguity between function declarations and function expressions can be correctly identified by the parser. So, the assignment, the logic, even the comma, various operators can tell the parser, and the function to use the unary operation can be counted as the fastest way to eliminate ambiguity, the common exclamation point is just one of them. Any method that can turn a function into a function expression allows the parser to call the definition function correctly.
For example:
! function () { console.log (' Hello world! ' );} (); // Output Hello world
and omitted! The words:
function () { console.log (' Hello world! ' );} ();
is understood as a function declaration, and the function declaration does not have a name to give an error. If there is a function name:
function f () {Console.log (' Hello world! ' );} ();
will still be an error, because function f () {} functions declaration is promoted, equivalent to:
function f () { console.log (' Hello world! ' // other code ... // error here.
Ps:
If you don't care about the return value, these unary operations are valid
+function() {alert (' Hello world! ')} () // NaN-function() {alert (' Hello world! ')} () // NaN~function() {alert (' Hello world! ')} () // -1
If you have any questions, please leave a message (???)
Anonymous functions in JavaScript meet! What's going to happen?