Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the role of the parentheses in the following piece of code?

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?

like image 554
Emanuil Rusev Avatar asked May 30 '10 09:05

Emanuil Rusev


2 Answers

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.

like image 86
Darin Dimitrov Avatar answered Sep 29 '22 17:09

Darin Dimitrov


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.

like image 43
halfdan Avatar answered Sep 29 '22 17:09

halfdan