In the Node Module System portion of the “Complete Node.js Course”, Mosh talks about the order of setting export variables.
For example, we can have something like this:
function hello(name) {
console.log("Hello", name);
}
var name = "kaushik";
module.exports = hello;
module.exports.name = name;
However, we cannot set it in this order:
module.exports.name = name;
module.exports = hello;
I am not really understanding what is going on in the background, since in the first example, we are setting a variable to be a function and then setting a property of that function to be a variable (?!?)
And I am not sure why that is any better/worse in the example when the order is switched.
I would really appreciate any help to understand what is going on in the background!
module.exports
starts off as an empty object, {}
. So by doing this…
module.exports.name = name;
you’ve added a name
property to that object.
But then when you do this…
module.exports = hello;
you’ve completely replaced that object with the hello
function i.e. module.exports
now refers to the function, not the original object.
But if you flip that around and do this first…
module.exports = hello;
you’ve still replaced that object with the function, but then this…
module.exports.name = name;
adds a name
property to the function, as you suspected. So you end up exporting both the function and the name. Though it’s a bit weird! You could also export them separately, like this…
module.exports.hello = hello;
module.exports.name = name;
in which case the exported object will have a hello
property which refers to the function and a separate name
property which refers to the name.
1 Like
That makes a little more sense; thanks!