36

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.

Community
  • 1
  • 1
Shaoz
  • 10,573
  • 26
  • 72
  • 100
  • 1
    same question here: http://stackoverflow.com/questions/3921922/what-does-this-mean-function-x-y-a-b-in-javascript/3921997#3921997 – DoXicK Oct 28 '10 at 14:14

5 Answers5

56

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)
pex
  • 7,351
  • 4
  • 32
  • 41
11

You are making a function that is immediately being called, with someWord as a parameter.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
7

It's a way to define an anonymous function and then immediately executing it -- leaving no trace, as it were. The function's scope is truly local. The () brackets at the end execute the function -- the enclosing brackets are to disambiguate what is being executed.

fish2000
  • 4,289
  • 2
  • 37
  • 76
7

Basically this lets you declare an anonymous function, and then by enclosing it in parentheses and writing (someWord) you are running the function. You could think of it as declaring an object and then immediately instantiating the object.

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
7

It's used to create anonymous function (function without name that can be "nested" inside other function) and pass argument to that function. The someWord is passed as argument, and the function can read it using the keyword "arguments".

Simple example of usage:

function Foo(myval) {
    (function(){
      // Do something here
      alert(arguments[0]);
    })(myval); //pass myval as argument to anonymous function
}
...
Foo(10);
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208