Harold Harold - 3 months ago 10
Javascript Question

Why must I immediately invoke an immediately invoked function expression?

If I have:

var calc = function(){
return {
adder: function(x,y){return x+y;}
}
};
calc();
calc.adder(4,5);


calc.adder is undefined. However, if I immediately invoke calc as

var calc = function(){
return {
adder: function(x,y){return x+y;}
}
}();
calc.adder(4,5);


things work as expected. Why does the first example fail?

Answer

First code set

calc() is a function that returns an object that contains a function called adder(). So this will work.

var calc = function(){
    return {
        adder: function(x,y){return x+y;}
    }
};

var cal = calc();
cal.adder(4,5);

The line of code

calc();

Stores the returned object in no variable, so you can't use the object.

Second code set

The second example you posted is essentially the same thing. The calc variable is no longer a function, it is the object that the un-named function returns when you execute it with the ();