Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  26] [ 6]  / answers: 1 / hits: 18015  / 11 Years ago, sun, june 16, 2013, 12:00:00

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?


More From » javascript

 Answers
14

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.


[#77600] Friday, June 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cody

Total Points: 679
Total Questions: 111
Total Answers: 111

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;