Difference between exporting a function and an IIFE in Javascript

Asked

Viewed 195 times

4

Is there any difference between:

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

And:

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

Taking into account the context of exporting and importing modules?

  • The () after the function means that it will be executed immediately after your declaration.

  • This creates some difference in the context of exporting and importing modules?

  • In that context I can’t explain. :(

  • See if this helps: https://answall.com/questions/13364/70

  • No. I already know that. I just want to know if there is any difference between the two in the context of modules (export and import), as said in the above comment... :/

1 answer

2


Nothing changes in the "module import and export context". What will really change, between the two examples, is the value which will be exported.

In the first example:

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

See that we have a IIFE, which means that it will be executed soon after your declaration. Thus, the value exported by module.exports will be the value that is 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 an IIFE-wrapped value to 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 the require.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.