The Google Analytics tracking code looks like this:
(function() {
code
})();
What’s the technique they are using with those brackets – (stuff)() – called? What does it do?
I put the Google Analytics code before the closing head tag on my page and then put an if statement around it like this (I include a Jquery cookie plugin further up):
<script type="application/javascript">
if ($.cookie('allowcookies') == 'yes') {
analytics code
}
</script>
It didn’t run until I used the same technique around my code:
(function() {if ($.cookie('allowcookies') == 'yes') {
analytics code
}
})();
Why did it not run before I did that? Why did it run after?
It’s commonly known as «self executed anonymous function (¹)» (o «immediate function invocation») and its main use is to avoid the creation of variables into the global (or in the outer) scope.
It’s also used as shortcut when you want to create a function to execute just once, without the need to first define the function with its own identifier and then soon make the function call.
It may be eventually used inside a scope and then it may create a closure if the outer context (or other references) are binded through parameters passing, e.g.
Another practical use I make with this expression is when I need to create a function to be soon executed inside a constructor function when it is called with
newkeyword (instead of an explicit call to someinitmethod).(¹) — as stated on book “Mantainable Javascript” by Nicholas Zakas (O’Reilly, ISBN 978-1-449-32768-2) page 44, the suggested expression is
(function() {}()), with nested parens (even if(function() {})()will work anyway)See also Immediate function invocation syntax