5

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?

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
Emanuil Rusev
  • 34,563
  • 55
  • 137
  • 201

2 Answers2

11

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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 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 May 30 '10 at 09:37
  • @jasonmp85, wrong, foo = function(){}; has the same semantics as function foo(){}, just different syntax. – Martin Konecny May 30 '10 at 10:27
  • @teehoo I didn't say anything to the contrary – jasonmp85 May 30 '10 at 11:53
2

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.

Community
  • 1
  • 1
halfdan
  • 33,545
  • 8
  • 78
  • 87
  • I'm no javascript expert, but why put that code in a lambda function instead of just putting it in directly? – Onots May 30 '10 at 09:25
  • 1
    To prevent the variables from getting overwritten by any other JS-code. – halfdan May 30 '10 at 09:26
  • 4
    The variables getting overwritten isn't really a problem -- they're simply trying to avoid "polluting" the global namespace. – James May 30 '10 at 09:35
  • Yep, properly scoping things in Javascript is all about using closures and lambdas. In fact most "modules" are really just big closures. – jasonmp85 May 30 '10 at 09:40