Difference between exporting a function and an IIFE in JavaScript

Is there any difference between:

module.exports = (function() {
  // Code.
})();

E:

module.exports = function() {
  // Code.
};

Taking into account the context of exporting and importing modules?

Author: Luiz Felipe, 2018-01-20

1 answers

Does not change anything in the "module export and import context". What will really change, between the two examples, is the value that will be exported.

In the first example:

module.exports = (function() {
  // Code.
})();

See that we have a IIFE, which means that it will be executed right after your declaration. Thus, the value exported by module.exports will be the value returned by it. Thus:

module.exports = (function() {
  return 'Luiz Felipe';
})();

The module in question would export the value 'Luiz Felipe', and not a function.

However, most of the time, this is completely unnecessary, since the scope of the modules is private to other files, so there is really no need to export a value wrapped by an IIFE to the Node.js.


In the other case:

module.exports = function() {
  // Code.
};

The module would export the function itself, not the value returned by it. To get your return, you would need to run it after importing it, using require.

 2
Author: Luiz Felipe, 2020-01-06 19:02:07