If module.exports is assigned an object, either by a variable name or an object literal, does it have access to variables defined outside of module.exports within the same file?

Question

If module.exports is assigned an object, either by a variable name or an object literal, does it have access to variables defined outside of module.exports within the same file?

Answer

The object being assigned to module.exports will have access to other variables that are defined within the same scope, however if those other variables are not also being exported, we will not have access to them in the file importing the module.

For example:
moduleToExport.js:

const myVar = {
  prop1: 'prop 1'
}

const objToExport = {
  key1: myVar.prop1
}

module.exports = objToExport;

main.js:

const myModule = require('./moduleToExport.js'); //require the exported module which is the objToExport object

console.log(myModule); //logs the object `{ key1: 'prop 1' }` to the console, which does not include a reference to the variable myVar
13 Likes

Hello,

Could you please give me an explanation about the declaration on the section INTERMEDIATE JAVASCRIPT MODULES >> 4. module.exports II:

You are asking for a declaration of an module export + anonymous function and I did this:

module.exports = {
  myAirplane: "CloudJet",
  displayAirplane: () => {
    return module.exports.myAirplane
  }
};

But I saw that you are using return this.myAirplane instead of return module.exports.myAirplane what would be the best practice or should I avoid the use of fat arrows functions and instead I have to use displayAirplane: function() {...;}?

Thanks in advance for your patience.

1 Like

I believe it’s just programmer preference. You are trading typing () => instead of function() for having to type module.exports instead of this. Both work, so do what you prefer.

1 Like

Great! thanks I’ll keep in mind.

1 Like

Or as the shortest and most concise alternative, you could also just use the ES6 syntax and write

displayAirplane() {
   return this.myAirplane;
}
1 Like

Or this…

displayAirplane: () => this.myAirplane

1 Like

I tried this way, but then the following happens:
console.log(Airplane); // will print { myAirplane: ‘CloudJet’,
// displayAirplane: [Function: displayAirplane] }
console.log(Airplane…displayAirplane()); // will print javascript_modules-airplanes/2-
// airplane.js:6 return undefined.myAirplane;