39

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.

1

5 Answers 5

59

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)
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the response, it makes sense now
Can this function be given a name? or does it have to be anonymous?
12

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

1 Comment

Wow, this is the sharpest answer and I get it. thanks
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);

Comments

7

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

Comments

6

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.