Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between function(){}() and !function(){}() [duplicate]

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

So I was just reading through the source of the new Bootstrap (2.0) from Twitter and noticed that there is an exclamation mark before the self-invoking anonymous function. When I saw this I immediately thought "Oh crap, there's a new, better way to do this?".

See for yourself!

  • http://markdotto.com/bs2/js/bootstrap-modal.js
  • http://markdotto.com/bs2/js/bootstrap-dropdown.js
  • http://markdotto.com/bs2/js/bootstrap-scrollspy.js
  • http://markdotto.com/bs2/js/bootstrap-popover.js
  • http://markdotto.com/bs2/js/bootstrap-tooltip.js
  • http://markdotto.com/bs2/js/bootstrap-tab.js

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

Another thing I noticed was the "use strict" right after this. I don't think it's related to my previous inquiry, but can anyone explain this?

Thanks!

like image 867
Johnny Avatar asked Jan 25 '12 17:01

Johnny


2 Answers

function(){} ();

By itself (see Point's comment) isn't going to be valid, since

function() {}

is a function declaration. To invoke it immediately, you need to get the JavaScript engine to treat the function as an expression. People usually do this as either of

(function(){}) ();  //more common

(function(){} ()); // Papa Crockford's preference:

with

!function(){}();

simply being a shorthand version of the same thing.

like image 69
Adam Rackis Avatar answered Nov 10 '22 17:11

Adam Rackis


If you have 2 scripts:

script1.js:

(function(){

})()

script2.js:

(function(){

})()

And you concatenate them, you get:

(function(){

})()
(function(){

})()

This causes an error, while:

!function(){

}()
!function(){

}()

Doesn't.

like image 38
Esailija Avatar answered Nov 10 '22 15:11

Esailija