3

Possible Duplicate:
What does this mean? (function (x,y)){…}){a,b); in JavaScript

(function(){
    var foo = 'Hello world';
})();

i don't know what's use of it? and what's meaning of it/?

Community
  • 1
  • 1
runeveryday
  • 2,751
  • 4
  • 30
  • 44

3 Answers3

6

On its own it does nothing except declare a variable that isn't used - it should invoke some other functions to do something useful.

That said, what you have is an immediately invoked function expression, i.e. an anonymous function:

function() { ... }

which is invoked with no parameters:

(f....)();

The rationale is two fold:

  • it allows the function to be defined and called without giving it a name in the global name space
  • any variables defined within the function are also held within that scope, and don't pollute the global name space.
Alnitak
  • 334,560
  • 70
  • 407
  • 495
3

It's an anonymous function that executes immediately.

The idea is to create a private scope. Often one would return a closure from the anonymous function that retains access to variables created in that scope.

For example

var greet = (function () {
    var foo = 'Hello world';
    return function () {
        alert(foo);
    }
}());

greet();
mhyfritz
  • 8,342
  • 2
  • 29
  • 29
0

This calls an anonymous function immediately.

Have a look here: What does this “(function(){});”, a function inside brackets, mean in javascript ?

Community
  • 1
  • 1
pex
  • 7,351
  • 4
  • 32
  • 41