0

So I'm reading some node.js-modules in a school example app, and they are all instantiated in a function like this:

(function() {
    "use strict";

    // Some declarations

    module.exports = some value;
}());

That is, they are all encapsulated by an anonymous function like this:

(function() {
    // Module
}());

Does anyone know what the purpose may be for doing so? Has it something to do with efficiency?

Jesper
  • 1,819
  • 3
  • 12
  • 40
  • 1
    If they’re actually Node.js modules and are never used in a browser, there is no point in doing this. Node does it automatically. – Ry- Apr 05 '17 at 08:22
  • ..but if it's a school example app, they might do it just to enforce the habit when you're writing browser JS. – JJJ Apr 05 '17 at 08:24
  • 1
    It is a common pattern for restricting variable scope as the contents are executed immediately yet no contents leak to the global/window namespace. Definitely isn't necessary in node.js as once a module is required, the contents of the module are evaluated by default with the scope being restricted to the module. – Kevin Reilly Apr 05 '17 at 08:25
  • Looks to me as if the parentheses are wrong? `(function() { ... })();` – Arg0n Apr 05 '17 at 08:27
  • @Arg0n [Both do the same thing](http://stackoverflow.com/questions/38194964/immediately-invoked-function-expression-where-to-put-the-parenthesis). Your version is more common. – JJJ Apr 05 '17 at 08:31
  • @JJJ So the parentheses surrounding the `function` is not needed? `function() { ... }();` – Arg0n Apr 05 '17 at 08:32
  • @Arg0n What? The code in the question has parentheses around the function. – JJJ Apr 05 '17 at 08:33
  • @JJJ Yeah, I was just curious. Seems it does not work tho. – Arg0n Apr 05 '17 at 08:34
  • @Arg0n It does work! – Jesper Apr 05 '17 at 08:34
  • @Jesper Yeah, but not without parentheses surrounding function. `(function() { console.log('test') }()); //Works`, `function() { console.log('test') }(); //Error` – Arg0n Apr 05 '17 at 08:35

0 Answers0