Thomas Christopher Davies Thomas Christopher Davies - 1 month ago 13
Javascript Question

Javascript: Syntax creating private object properties

due to learning new things I came across how to make things private and public. The basic idea to me is clear. But just in terms of how it is built I got a specific question:

var NOW = (function(){
var privateVariable = 5;
var privateFunction = function(){};
return{
publicVariable: 4,
publicFunction: function(){}
};
})();


So my question is why is function wrapped inside brackets (parentheses)?

var NOW =
(
function(){...}
)
();

Answer

They're optional in that code, this also works fine:

var NOW = function(){
    var privateVariable = 5;
    var privateFunction = function(){};
    return{
        publicVariable: 4,
        publicFunction: function(){}
    };
}();

People are in the habit of wrapping functions that they're going to immediately invoke in () because if you aren't assigning the result to something (or similar), it's necessary to tell the parser that the function keyword is starting a function expression rather than a function declaration. E.g., this is not okay:

function() { alert("foo"); }();

Because when the parser encounters function where it could be expecting a statement, declaration, or expression, it assumes it starts a declaration. So we do this:

(function() { alert("foo"); })();

or this:

(function() { alert("foo"); }());

or any of several other things (see this question's answers) to put the parser in the mode where it's expecting an expression, not a statement or declaration.

Comments