0

I've come across two different methods of defining routes in Node.js:

Method #1:

router.get("/", (req, res, next) => {
    res.render("index", { title: "ABC" });
});
module.exports = router;

Method #2:

module.exports = (() => {
    router.get("/", (req, res, next) => {
        res.render("index", { title: "ABC" });
    });
    return router;
})();

I was curious, what's the main difference between these two? And, is there a major reason why one method is preferred over the other? Thanks!

user3781239
  • 141
  • 4
  • 13
  • 1
    The result is the same. The difference is just a matter of style and whether you prefer to specify the `module.exports` at the top of the module rather than at the end. – Jonathan Lonowski Jun 05 '17 at 04:23
  • @JonathanLonowski got it, thank you! I knew that functionality they would do the same but I thought there was some hidden reason why one method was preferred over the other. – user3781239 Jun 05 '17 at 04:25
  • #2 also might be a habit kept from client-side development, as it resembles the [revealing module pattern](https://stackoverflow.com/questions/5647258/how-to-use-revealing-module-pattern-in-javascript). Such patterns aren't typically necessary with Node.js since it has its own module isolation feature with `exports` and `require()`. – Jonathan Lonowski Jun 05 '17 at 04:37

1 Answers1

1

Method #2 is ES6 syntax with arrow function syntax being used. Both perform the same functionality, only difference is the syntax.

Gurdev Singh
  • 1,996
  • 13
  • 11