5

I'm working on some code where a given page has many .js files associated with it (utilizing them like libraries). Each .js file looks like this inside:

(function() {
    .... all the lib functions and objects ....
})();

After some playing, I see that functions of the format (function() {...})(); get called automatically. If I strip away the outer paren's to have function() {...} then the code is invalid. If I add a function name then the code is valid but does not run till called function foo() { ... }.

Is there a special reason the lib has been written in this way? I would guess it would encapsulate variable names and such. What is it about the syntax of this that allows it to be run automatically on page load?

flacnut
  • 830
  • 3
  • 9
  • 20

3 Answers3

6

That's called an IIFE, an Immediately-Invoked Function Expression.

It lets you define variables, including functions, which aren't visible from the outer scope and doesn't encumber the global name space.

(function() {
    var v = ... // this variable can be used in the IIFE but not from outside
})();

The reason why you need the outer parenthesis is because a statement starting with function something is interpreted as a function declaration, which here would be invalid because a function declaration needs a name. You have to use a trick to make it an expression. Parenthesis do that, but you could have used other tricks, for example

+function(){
  ...
}();

but the outer parenthesis is the clearest and probably the less surprising solution.

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
  • Thanks, the bit that I was really looking for is what you say second, about how it gets executed as an expression. – flacnut Jun 16 '13 at 18:40
1

Most of the libraries are anonymous functions with no name.

So it would need to be executed immediately. As you cannot call a function later which has no name and has to be invoked immediately.

Sushanth --
  • 53,795
  • 7
  • 57
  • 95
1

What is it about the syntax of this that allows it to be run automatically on page load

It's not called on page load, it's called right after the declaration. And that's because the calling parentheses are included:

})();
  ^^

If I strip away the outer paren's to have function() {...} then the code is invalid.

That's a known JavaScript syntax quirk: it has to be considered an function expression to be able to be immediately invoked; otherwise, it's interpreted as a function declaration, which cannot be called immediately.

Is there a special reason the lib has been written in this way? I would guess it would encapsulate variable names and such.

Yes, most likely to keep the global namespace clean.

bfavaretto
  • 69,385
  • 15
  • 102
  • 145