About Anonymous Functions in Javascript

Viewed 1099

I am new in Javascript, but have deep background real OO languages like C#, Java, C++... In Javascript there is a concept called anonymous functions. Here is a sample code:

(   function() { 
      for(var x = 0;x<5;x++) {
         console.log(x); 
      } 
   })(); 

As I have understood the parantheses at the end make the function call itself. There is also another syntax which does the same:

var x =   function() { 
      for(var x = 0;x<5;x++) {
         console.log(x); 
      } 
   }(); 

But right now if I try to use x, it does not execute the function again. So what is the goal if using the assignment in the second version? Can I use the function via x again?

3 Answers

Self executing function are known as IIFE (Immediately-Invoked Function Expression), it is usually used to control the scoping so you don't end up with a lot of global variables.

For example, this function act as a moneybox, it encapsulate all information of your "money", so you can only insert money or get the total money, but you can't directly call add/get and access the variable.

It can be used as a form of OOP as well, since you are already very familiar with it

var myMoneyBox = (function() {
    var money = 0;

    function addMoney(x) {
        if (x > 0)
            money += x;
    }

    function getMoney() {
        return money;
    }

    return {
        add: addMoney,
        get: getMoney
    }
})();

myMoneyBox.add(10);
console.log(myMoneyBox.get());

x is assigned the result of your function, just like in any other expression x = f(), you just define f within the expression. It doesn't have a return value so in this case the value of x is undefined.

If you want to use x to call the function, then just don't add the () to the end of the expression...

I think this could help you:

var x =   function() { 
      for(var x = 0;x<5;x++) {
         console.log(x); 
      } 
   }; 
x();

Related