How useful is the Exclamation Point (!) before declaring functions in Javascript?

14

I was reading a manual, and was asked to start the functions like this:

!function (){

}();

This exclamation point appeared. What is the purpose of it?

    
asked by anonymous 06.10.2016 / 20:27

4 answers

21

Try removing the exclamation mark to see what happens. Open the console. It will give a syntax error, and the function will not execute.

JavaScript syntax interprets the function as a statement only if the line begins with function (ignoring spaces and tabs). Function statements can not be immediately executed with () at the end, only expressions can ( more about the difference between declaration and expression of functions ). So the NOT operator in this case is just a trick to force the interpretation of the function as an expression and allow it to be executed immediately. There are other ways to do this, such as using the unary operator + or parentheses, among others:

+function() {
   // ...
}();


(function() {
   // ...
}());
    
06.10.2016 / 20:58
8

The ! before the function causes it to be treated as an expression, so that we can call it:

!function () {}()

This will also return the opposite boolean of the return value of the function, in this case true , because !undefined is true .

    
06.10.2016 / 20:35
7

Note this code:

!function (){
    return true;
}();

Here's what it does:

false

Already another code:

!function (){
    return false;
}();

Produce this:

true

That is, it reverses the result of the function.

To understand how it works, let's split the program into three parts:

  • !
  • function() { ... }
  • ();

And so let's start with the second part, function (){ ... } , which declares an anonymous function.

By joining the second part with the third, (); , we have that the anonymous function declared in the second part will be invoked immediately, producing as a result whatever is returned by that function.

When you join the first part, ! , with the second and third, we have to reverse the given value as a result of invoking the anonymous function.

    
06.10.2016 / 20:51
5

The! in javascript is used to invert a boolean expression.

In this case, since it precedes a function, if the function returns true, the result will be false and vice versa.

It works as the NOT operator.

    
06.10.2016 / 20:32