views:

67

answers:

2

This is the tracking code for Google Analytics:

var _gaq = _gaq || [];
_gaq.push(["_setAccount", "UA-256257-21"]);
_gaq.push(["_trackPageview"]);

(function() {
var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true;
ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s);
})();

You can see that the function is inside parentheses.

Why do you think is that?

+7  A: 

It is an anonymous function that is defined and invoked immediately. It cannot be invoked from the outside as it has no name. All the variables inside will be scoped to the anonymous function. This could be used to do some processing on the global scope without adding new members to it.

Darin Dimitrov
Well, a function with no name can be invoked if you assign it to a variable and then call it using that variable (it's still an anonymous function, just stored in a variable that happens to have a name).
jasonmp85
@jasonmp85, wrong, foo = function(){}; has the same semantics as function foo(){}, just different syntax.
teehoo
@teehoo I didn't say anything to the contrary
jasonmp85
+2  A: 

This is a so called lambda function. As you can see, it has no name and is immediately called using the brackets at the end of the line.

halfdan
I'm no javascript expert, but why put that code in a lambda function instead of just putting it in directly?
Onots
To prevent the variables from getting overwritten by any other JS-code.
halfdan
The variables getting overwritten isn't really a problem -- they're simply trying to avoid "polluting" the global namespace.
J-P
Yep, properly scoping things in Javascript is all about using closures and lambdas. In fact most "modules" are really just big closures.
jasonmp85