What does this "(function(){});", a function inside brackets, mean in javascript?

Shaoz picture Shaoz · Oct 28, 2010 · Viewed 15.7k times · Source

Possible Duplicates:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
What do parentheses surrounding a JavaScript object/function/class declaration mean?

Hi All

I don't know what the following does:

(function(){
  // Do something here
  ...
})(someWord) //Why is this here?;

My questions are:

  1. What's the meaning of putting a function inside brackets .i.e. (function(){});?
  2. What do the set of brackets do at the end of a function?

I usually see these in jquery codes, and some other javascript libraries.

Answer

pex picture pex · Oct 28, 2010

You're immediately calling an anonymus function with a specific parameter.

An example:

(function(name){
  alert(name);
})('peter')

This alerts "peter".

In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:

jQuery.noConflict()
(function($){
  var obj = $('<div/>', { id: 'someId' });
})(jQuery)