0
    (function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  provide({
    getDayName: function(number) {
      return names[number];
    },
    getDayNumber: function(name) {
      for (var number = 0; number < names.length; number++) {
        if (names[number] == name)
          return number;
      }
    }
  });
})();

show(getDayNumber("Wednesday"));

Now i am reading an eloquentjavascript.net and i found such module pattern there. But i find it a little bit confusing, so can you explain to me why do we need to put this after our function - >() . It is to make it self invoking as far as i understand. but why do we need to make it self invoking?

And the second question why do we need to put our function in brackets (function ) () .Is ii just syntaxis ?

user2114177
  • 273
  • 1
  • 9
  • 18
  • Because otherwise, it will never run. – SLaks Oct 27 '13 at 13:13
  • http://stackoverflow.com/questions/8228281/what-is-this-construct-in-javascript 1) The trailing `()` before the `;` invoke the `function` immediately. 2) The other parenthesis around the `function` distinguish it as an *Expression* so it can be invoked immediately (`function` statements/declarations don't allow it). – Jonathan Lonowski Oct 27 '13 at 13:20

1 Answers1

3

The point of immediately-invoking functions is twofold: firstly, most obviously, they invoke themselves immediately. Secondly, all variables defined within the function are encapsulated within that function.

For example:

(function () {
    var foo = "bar";
    window.bar = foo;
})();

After this function executes, bar will be accessible outside of the function, but foo will not.

As for enclosing the function in brackets, this causes the function to be treated as an expression, which can then be executed.

( function (a) { console.log(a); } ) ("foo");

In the above, "foo" will be logged. Without the brackets, you'll get a syntax error.

EDIT

It's also worth noting that you can use (and will occasionally see) !function instead of (function) to make the function an expression:

!function () {}();

Which is the same as

(function () {})();

With the exception that it converts the return value to a Boolean, which is negated, but ignored in most cases anyway.

azz
  • 5,852
  • 3
  • 30
  • 58