Why would a javascript function be wrapped as anonymous?

advertisements

In reading a technical education post I came across this sample code from the author..sterilized of course. The content of the functions is not what I found curious and everything worked as the author had described.

What caught me was wrapping the function in an anonymous (I think that's what they did) function. The only thing I can see with my meager knowledge is that it creates a grouping/container.

Why is this and should I make a habit of this..I understand the second half may be subjective so disregard if too obtuse.

(function ()
{
   FuncName1 = function (var1, var2, var3)
   {
       ....code n stuff....
   }

   FuncName2 = function (var1, var2)
   {
    .....code n stuff...
   }
 })();


Excellent explanations everyone. Thank You. So my follow on question would be then shouldn't every function be wrapped? For example the author wrapped two functions in one "scope or module". Couldn't those leak into each other?


So cookie monster to make the authors code even better I would do as such:

(function ()
{
   var FuncName1 = function (var1, var2, var3)
   {
       ....code n stuff....
   }

   var FuncName2 = function (var1, var2)
   {
    .....code n stuff...
   }
 })();

The key as you say in your comments is by using the keyword var keeps them in scope of the containing anonymous function. Not using var results in an implicit global scope.


Like the guys said above it creates modular code. If you set the anonymous function to return "things" and you set that to a variable you now have a closure that has name spaced goodness.

var name = (function() {

   var
       lastName = 'Moody',
       firstName = Hank
   ;

   return {
      setName: function(newFirstName, newLastName) {
                   firstName = newFirstName;
                   lastName = newLastName;
                },
      getName: function() { return firstName + " " + lastName; } 

    }

}());

Now you can get and set the code and it lives in it's own scope! Bam - Modular Design Pattern.

name.setName('Clark', 'Kent');
console.log(name.getName); // Will now output Clark Kent

Very powerful and simple design pattern.

Update:

Almost forgot the most important thing their name - IIFE or immediatetly invoked function expression!