2

Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?

I simply don't understand the usage of...

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

...thing.

I call that a 'thing' couse' I dont even know its name...

Is this a shorthand for onReady or onLoad event or it is for some kind of scope or closure thing?

If can anyone explain the usage and purpose of this syntax would be appreciated.

Community
  • 1
  • 1
Lupus
  • 1,519
  • 3
  • 21
  • 38

2 Answers2

4

It's known as a self executing function - It calls itself after its declarations.

Commonly used not to pollute the global namespace.


For a short but interesting article have a read here:

How Self Executing Functions Work

cillierscharl
  • 7,043
  • 3
  • 29
  • 47
3

Is this a shorthand for onReady or onLoad event or it is for some kind of scope or closure thing?

It is self-invoking anonymous function.

It invokes itself due to () at the end because that's how you normally invoke a function:

someFunc();

It is anonymous because it has no name.


The whole function body is wrapped in () to create local scope of variables inside it. Any variable/function declared in that way won't be available outside (so that global scope is not polluted) unless exposed explicitly.


You can learn more about it here.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578