2

I am learning module pattern in Javascript, and have come across these two ways to create a module:

var Module = (function () {
  // code
})();

var Module = (function () {
 // code
}());

is there a significant difference in these two approaches? if not, which is considered the better practice? Thanks.

software_writer
  • 3,941
  • 9
  • 38
  • 64
  • 1
    No, there isn't. This is a duplicate, I'll find the earlier version. – T.J. Crowder Feb 28 '16 at 18:24
  • In this case, there is no difference. As for the modules, you can read about commonjs and amd. Just as an example I advise to look typescript, the code that will be generated can be used to form a idea of the structure of the module – Pyfhon Feb 28 '16 at 18:25
  • Thank you @T.J.Crowder for finding the the right answer. That answers my question. – software_writer Feb 28 '16 at 18:41

1 Answers1

0

Both are the same. The outer round braces are forcing the inside code to be evaluated as an expression. This means that in both cases the function code is treated as function-expression as well. And then this function is immediately executed due to () braces.

So, it should be exactly the same from the point of view of JS interpreter todo list: 1) get function expression, 2) execute it right away.

It only differs from aesthetic point of view - which way it looks more natural for you.

Hero Qu
  • 911
  • 9
  • 10