DEV Community

Cover image for Difference between exports and module.exports
Dhanush N
Dhanush N

Posted on • Originally published at dhanushnehru.hashnode.dev

3

Difference between exports and module.exports

The module represents the current module in the plain Javascript object.

Exports is a plain JavaScript variable. Module is a plain javascript object which has the exports property

From one module to another, when we want to export a single class, variable, or function, we use modules. exports.

From one module to another, when we want to export multiple variables or functions, we use exports.

var module = { exports: { value1: 10 , value2: 20 } };
var exports = module.exports;

return module.exports;
Enter fullscreen mode Exit fullscreen mode

In the above example, we have assigned multiple values to the same object.

module.exports.value1 returns 10 and module.exports.value2 returns 20

var module = { exports:  10  } };
var exports = module.exports;

return module.exports;
Enter fullscreen mode Exit fullscreen mode

In the preceding example, exports is set to a value that results in modules.Exports are no longer the same object.

module.exports returns 10

const userDetails= (data)=>{
    return {
        getUsername:()=> data.username,
        getEmail:()=> data.email,
   }
}

module.exports = userDetails;
Enter fullscreen mode Exit fullscreen mode

In the preceding example, calling userDetails(data>) returns the value of the username.getUsername()

const getUsername:(data)=> data.username

const getEmail:(data)=> data.email

exports.getUsername = getUsername;
exports.getEmail = getEmail;
Enter fullscreen mode Exit fullscreen mode

In the above example the value of username can be got by getUsername()

If we go with the first approach, we do not need to include new lines in the export statement each time we create a new function.

Whereas in the second approach new functions if created gradually increases the number of lines of the exports statement as well

Therefore, as a best practice in accordance with the NodeJs documentation's usage of exports and module.exports, we can avoid using exports and instead use module.exports.

Thanks for reading ❤️. I hope you liked it.

Follow me via Twitter, Instagram, or Github.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up