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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay