Search code examples
javascriptiife

Can anyone explain the output for this code which is based on the concept of IIFE (Immediately Invoked Function Expression)


(function(value){

    var names = ["January","February","March","April","May","June","July",
                  "August","September","October","November","December"];

    value.name = function(number){
            return names[number];
    };

    value.number = function(name){
            return names.indexOf(name);
    };
})(this.month = {});

console.log(month.name(2));
console.log(month.number("November"));

Please help me explaining how this program works. I didn't understand why a new object is created outside the function and why this operators used.


Solution

  • this will be the global object (since it isn't being used inside a function).

    this.month = {} assigns a new object to month on the global object.

    Assignments evaluate as the value assigned, so that gets passed to the function.

    This is, essentially, just an ugly and unintuitive way to write:

    function myFunction(value) {
    
        var names = ["January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December"
        ];
    
        value.name = function(number) {
            return names[number];
        };
    
        value.number = function(name) {
            return names.indexOf(name);
        };
    }
    
    var month = {};
    myFunction(month);
    console.log(month.name(2));
    console.log(month.number("November"));
    

    It uses this because you can't use var inside a the () used to call a function.