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/?

0

3 Answers 3

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

1 Comment

Every function expression without a name is an anonymous function.
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();

Comments

0

This calls an anonymous function immediately.

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

1 Comment

it's also called a closure sometimes, because all it does is to create a new scope

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.