1
(function () {
    // do somethig
})();

What means this function in parentheses? ()(); Some developers creates functions like this in js files directly.

Yair Nevet
  • 12,046
  • 12
  • 61
  • 101
barteloma
  • 5,342
  • 7
  • 55
  • 126
  • 1
    it's a function that's called as soon as it's declared. It's an idiom in JavaScript for providing quasi-anonymous namespaces (abusing the lexical closure nature of functions). – The Paramagnetic Croissant Jun 26 '14 at 06:59
  • Why the downvote? This is an important thing to know, and not easily googled if you don't know the keyword. – Thilo Jun 26 '14 at 06:59

2 Answers2

5

What means this function in parentheses? ()();

That means a self-invoking function in JavaScript.

Notice to the: (); - That is a calling.

Your function, which is anonymous BTW, will be invoked automatically without any caller intervention, but by itself, once it's declared.

In addition, as @Thilo suggested, it is also to get an isolated scope for local variables.

Yair Nevet
  • 12,046
  • 12
  • 61
  • 101
  • And the reason people do this is to get an isolated scope for their local variables. – Thilo Jun 26 '14 at 07:01
  • If I use this self-invoking function in a js file and call it in an html file, it works immmediately. Do you mean this? – barteloma Jun 26 '14 at 07:25
  • @bookmarker It doesn't matter if you call it inline in your HTML (with `script` tag) and in an external `.JS` file. – Yair Nevet Jun 26 '14 at 07:26
4

this is the self invoking anonymous function. This means the function within the first () parenthesis is the function which has no name and by next (); parenthesis you can understand that it is called at the time it is defined. And you can pass any argument in this second () parenthesis which will be grabbed in function which is in the first parenthesis. see this example:

(function(obj){
    //do something with this obj
})(object);

here the 'object' you are passing will be accessible within the function by 'obj', as you are grabbing it in the function signature.