3

Possible Duplicates:
Is the following JavaScript construct called a Closure?
What do parentheses surrounding a JavaScript object/function/class declaration mean?
How does the (function() {})() construct work and why do people use it?
Difference between (function(){})(); and function(){}();

Hi,

As i was viewing a site with just simple html text and no graphics i thought of viewing its code.

When i did so i found this script

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-13137273-2']);
  _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);
  })();

</script>

is there is any special purpose of using code like the following

(function() { /*code;*/ })();

i have seen it in jquery. But still i am not much comfortable with the free style of extreme javascript programming.

Suggestions, comments and answers. Any would be nice.

THX

[i am writing this after the first answer. extreme in the sense ... which i did not find in other programming languages and which is unable for me to guess what that might be. besides there are lots of extraordinary option in javascript which i had mentioned as extreme. maybe i should have used another work.]

Community
  • 1
  • 1
Jayapal Chandran
  • 10,600
  • 14
  • 66
  • 91
  • Same as [What do parentheses surrounding a JavaScript object/function/class declaration mean? ](http://stackoverflow.com/questions/440739/what-do-parentheses-surrounding-a-javascript-objectfunctionclass-declaration). – Matthew Flaschen Dec 11 '10 at 08:13
  • Dup of [What does this javascript syntax mean?](http://stackoverflow.com/questions/511096/what-does-this-javascript-syntax-mean). – outis Dec 11 '10 at 08:14
  • Dup of [Init function in javascript and how it works.](http://stackoverflow.com/questions/4212149/init-function-in-javascript-and-how-it-works) – outis Dec 11 '10 at 08:21

3 Answers3

8

Suppose they had done it this way instead:

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-13137273-2']);
  _gaq.push(['_trackPageview']);

  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);
</script>

That would work the same way, but now the variables ga and s are global variables. If someone else writes other code with equally short, undescriptive variable names, they might happen to also use the same variables. In this case, it probably wouldn't cause much problem, but you might have the two pieces of code interfering with each other, because one of them defines s as something and then the other defines it as something else, and it makes debugging very tricky.

Try googling something like "Why are global variables bad?" for more information. This technique is a way of avoiding the creation of global variables.

Tyler
  • 21,762
  • 11
  • 61
  • 90
7

It limits the scope of the variables declared within the function to avoid littering the the global namespace.

It is a common good practice and there is nothing extreme about it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • extreme in the sense ... which i did not find in other programming languages and which is unable for me to guess what that might be. besides there are lots of extraordinary option in javascript which i had mentioned as extreme. maybe i should have used another work. anyway thank you for your comment. – Jayapal Chandran Dec 11 '10 at 08:17
4

One of javascript's cool features is anonymous functions, and this is an example of it.

With anonymous functions (aka first-class functions), you can assign functions to variables and pass them around as data, like this:

var foo = function(){return 4;}
var x = foo(); //x=4

In that example, foo(); is essentially the same thing as function(){return 4;}();. It turns out that both of those are valid javascript, and in both cases this stems from the fact that functions in javascript are first-class.

This opens up lots of cool possibilities. For example, you can return functions, pass functions as parameters, etc..


Edit: In your particular case, the reason an anonymous function is being used is to keep the variables used local and to avoid unecessarily adding variables to the surrounding namespace. This is similar to creating a {...} block in C, or for writing ((lambda () ...)) in scheme.

Cam
  • 14,930
  • 16
  • 77
  • 128
  • 1
    yes...it is an anonymous function, but you didn't really describe the purpose of having an argumentless function that's called immediately. – mpen Dec 11 '10 at 08:19
  • @Ralph: The other answerers have already covered that, so I didn't see it as necessary, but I suppose I could fix it for completeness' sake. (edit: added to answer) – Cam Dec 11 '10 at 08:21
  • You didn't mention it was an "add-on answer" ;) *Now* you've earned your +1. :p – mpen Dec 11 '10 at 08:39