7

Possible Duplicate:
Difference between (function(){})(); and function(){}();

I have seen it a lot by google:

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

Why they enclose their function inside the parethesis? Which is the difference between:

function(){/*code*/}

?

Edit

Ok the questions should have been this:

Why they enclose their code into this:

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

Instead to write the code directly into the js flow?
Are there any benefits, different behaviour?

Community
  • 1
  • 1
dynamic
  • 46,985
  • 55
  • 154
  • 231

5 Answers5

15

I usually use immediate functions to control the variable scope so as not to pollute the global name space. It's a very useful pattern.

(function (window, $, undefined) {
// This pattern gives you the following benefits:
//   * all variables defined in here are private
//   * can safely minify global variables: window, jQuery & undefined
//   * ensures that window, $, undefined mean what you expect
//   * global variables are localized so lookups are faster
}(this, jQuery));

So even if someone does window = ‘Bob’ or the shortcut $ doesn’t equal jQuery but instead is the Prototype library, the code inside this immediate function will still work correctly. While you may think to yourself “I’d never set undefined to something else”, keep in mind you’re not the only one putting code into the page; you can’t afford to have a poorly written ad script from DoubleClick bringing down the site, especially when it is so easily prevented.

JavaScript’s global scope is like a public toilet. You can’t always avoid it, but try to limit your contact with surfaces.

SavoryBytes
  • 35,571
  • 4
  • 52
  • 61
5

what you see is a self executing function:

var x = (function(bar){
    return bar;
})('foo')

alert(x);
ezmilhouse
  • 8,933
  • 7
  • 29
  • 38
  • @yes123: If it works, you can do *anything* you want. But this is a [known pattern](http://2007-2010.lovemikeg.com/2008/08/17/a-week-in-javascript-patterns-self-invocation/), and you should get acquainted with that kind of code. – rsenna Apr 01 '11 at 20:40
  • They are also called "iffees" in the JS world. IIFE immediately invoked functions – Peter Chaula Mar 06 '17 at 20:08
4

It's usually done to force the parser to treat it as a function expression and not a declaration.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    You should elaborate. Ie, `function foo(){}` is in the global scope and can be called via `foo()`, whereas `(function bar(){})` is not in the global scope. Calling `bar()` will cause a runtime error. – gilly3 Apr 01 '11 at 20:42
0

This is because usually the code looks like this:

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

The reason for the extra parenthesis is that this is not legal syntax:

function(){/*code*/}();
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
0

It's needed for immediate functions as @daniellmb said. See explanation of expression closure for more information.

RSG
  • 7,013
  • 6
  • 36
  • 51