views:

415

answers:

2

I am learning YUI and have occasionally seen this idiom:

 <script>
     (function x(){ do abcxyz})();
 </script>

Why do they create a function just to invoke it? Why not just write:

<script>
    do abcxyz
</script>

For example see here.

+39  A: 

They're taking advantage of closures.

A short explanation: Since JS uses function-level scoping, you can do a bunch of actions within a function and have it remain in that scope. This is useful for invoking code that doesn't mess with the global namespace. It also allows one to make private variables - if you declare a variable inside of an anonymous function and execute it immediately, only other code inside of the anonymous function can access that variable.

For example, suppose I want to make a global unique id generator. One might do code like this:

var counter = 0;
var genId = function()
{
    counter = counter + 1;
    return counter;
}

However, now anyone can mess with counter, and I've now polluted the global namespace with two variables (counter and genId).

Instead, I could use a anonymous function to generate my counter function:

var genId = function()
{
    var counter = 0;
    var genIdImpl = function()
    {
        counter = counter + 1;
        return counter;
    }

    return genIdImpl;
}();

Now, I only have one variable in the global namespace, which is advantageous. More importantly, the counter variable is now safe from being modified - it only exists in the anonymous function's scope, and so only the function genIdImpl (which was defined in the same scope) can access it.

It looks like in YUI's example code, they just want to execute code that doesn't pollute the global namespace at all.

Daniel Lew
+2  A: 

They want to avoid namespace collisions, I'd guess. Seems as a good practice in JS.

david a.