What is the difference between the functions () {} () and! Function () {} ()

Possible duplicate:
! function () {} () vs (function () {}) ()

So, I just read the source of the new Bootstrap (2.0) from Twitter and noticed that there is an exclamation mark in front of the self-starting anonymous function. When I saw this, I immediately thought: โ€œOh my gosh, is there a new, better way to do this?โ€

See for yourself!

Anyway, what's the difference? There must be a reason for this because they consistently use it in all of their JavaScript plugins (for Bootstrap).

Another thing I noticed is to โ€œuse strictโ€ right after that. I don't think this is related to my previous request, but can anyone explain this?

Thanks!

+6
source share
3 answers
function(){} (); 

By itself (see the comment on the point) will not be valid, since

 function() {} 

- function declaration. To call it immediately, you need to make the JavaScript engine treat the function as an expression. Usually people do it like from

 (function(){}) (); //more common (function(){} ()); // Papa Crockford preference: 

from

 !function(){}(); 

just being a shortened version of the same.

+14
source

If you have 2 scripts:

script1.js :

 (function(){ })() 

script2.js :

 (function(){ })() 

And you combine them, you get:

 (function(){ })() (function(){ })() 

This causes an error as well:

 !function(){ }() !function(){ }() 

not.

+8
source

ECMAScript Language Specification , Section 12.4, says:

Cannot start an ExpressionStatement application with the function keyword because it can make it ambiguous with FunctionDeclaration.

So, if you want the expression operator to perform an anonymous function, you need to get around this limitation. Adding ! (which simply negates the result of the function) makes it clear to the interpreter that this is not a declaration of the function, avoiding this ambiguity.

+3
source

Source: https://habr.com/ru/post/906887/


All Articles