(function(){
    //code
})();

is the module pattern and is widely used.
If you assign the result to a variable, there is no problem:

var result = (function(){
    //code
})();

But if you don't, since files are often gathered for perfomance, if a
file with something like that is before yours:

(function(){
    //code
})()

Note the missing ;, then it tries to us the result of it and to call
in with your function as argument. In fact it interprets:

(function(){
    //code
})()
(function(){
    //code
})();

As:

var f = (function(){
    //code
})();
f(function(){
    //code
})();

Which isn't what you want.

So some people add a ; before the ( in case the previous file forgot his.

About the !, it must be kind of the same idea but I don't know exactly
the difference...

On Tue, Sep 27, 2011 at 8:54 PM, Rob Griffiths <r...@bytespider.eu> wrote:
> Hi Pete
>
> The two are in fact !function(){}() and (function(){})()
> The first can be used where your immediately invoked function expression
> doesn't return anything
> However the second can be used when you do with to return a value.
> Ben Alman's article may help you
> more. http://benalman.com/news/2010/11/immediately-invoked-function-expression/
>
> --
> Rob Griffiths
> Twitter: @bytespider
> Github: https://github.com/bytespider
> bytespider.eu
> Sent with Sparrow
>
> On Tuesday, 27 September 2011 at 17:32, Pete wrote:
>
> Hi,
> could anyone explain me the difference in using "!" or ";" in front of
> "function() {}();"
>
> thanks
>
> pete
>
> //seen at
> https://github.com/twitter/bootstrap/blob/master/js/bootstrap-alerts.js
> !function( $ ){
> }( window.jQuery || window.ender );
>
>
> //seen at https://github.com/madrobby/keymaster/blob/master/keymaster.js
> ;(function(global){
> })(this);
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/jsmentors@jsmentors.com/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/jsmentors@googlegroups.com/
>
> To unsubscribe from this group, send email to
> jsmentors+unsubscr...@googlegroups.com
>
> --
> To view archived discussions from the original JSMentors Mailman list:
> http://www.mail-archive.com/jsmentors@jsmentors.com/
>
> To search via a non-Google archive, visit here:
> http://www.mail-archive.com/jsmentors@googlegroups.com/
>
> To unsubscribe from this group, send email to
> jsmentors+unsubscr...@googlegroups.com
>

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/jsmentors@jsmentors.com/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/jsmentors@googlegroups.com/

To unsubscribe from this group, send email to
jsmentors+unsubscr...@googlegroups.com

Reply via email to