Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript functions run automatically vs only when called [duplicate]

Tags:

javascript

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?

like image 611
flacnut Avatar asked Jun 16 '13 18:06

flacnut


2 Answers

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.

like image 156
Denys Séguret Avatar answered Sep 20 '22 06:09

Denys Séguret


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.

like image 30
Sushanth -- Avatar answered Sep 18 '22 06:09

Sushanth --