1

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(){...})();

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639

1 Answers1

4

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.

Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • 1
    Very well explained and very clear on what and why this convention is being used though it is not necessary in this case. Cheers –  Oct 24 '16 at 11:42