Questions on Article: implementing-modules-in-node

Hello,
I have some questions about the II lesson of Javascript Modules.
At the section module.exports the defined function celsiusToFahrenheit() used in the code snippet is assigned to module.exports.celsiusToFahrenheit to demonstrates the first way of exporting functions from a module.

1- Why it is:
module.exports.celsiusToFahrenheit = celsiusToFahrenheit;
instead of:
module.exports.celsiusToFahrenheit = celsiusToFahrenheit();
I understand that the way this works is to assign a new property to module.exports called celsiusToFahrenheit, I would expect that its value would be celsiusToFahrenheit(), but it seems it is called like a getter function would be called, without the parentheses, anyone can help me understand why’s that?.

2- Also, English not my native language, I don’t understand the sentence “exporting functions from a module”. Shouldn’t be “exporting to a module”, while for import “importing from a module”?

When you export a function, you just want to make it available in another module/file. The goal is to call that function in a context in the file which imports the function. That’s why you don’t add the parenthesis. With the parenthesis added, you would call the function in the very moment you export it.

When you export the function, you don’t specify which file receives the function/module. You just send it out. That’s why they wrote “from”.
Until you import the module with require() it’s somewhere in the orbit…

Oh ok, so, if I define a function, I can associate it to a variable at a later moment. Lol this is very basic but somehow I was completely missing this notion. Thanks!

function functionName(params){
//some code
};
const newFunctionName = functionName;
newFunctionName(params); //some code is executed

About the “from” or “to” thing, I still have some reserves instead. This code:

/* converters.js */
function celsiusToFahrenheit(celsius) {
  return celsius * (9/5) + 32;
}
 
module.exports.celsiusToFahrenheit = celsiusToFahrenheit;
 
module.exports.fahrenheitToCelsius = function(fahrenheit) {
  return (fahrenheit - 32) * (5/9);
};

I feel like it speaks to me this way:
“hey mate, I’m going to export the function celsiusToFahrenheit() from your file converters.js to module.exports, you can retrieve this function by importing it from module.exports to any other js file using require()”.

Am I understanding the logic behind correctly?

I would just change a little detail:
“hey mate, I’m going to export the function celsiusToFahrenheit() from your file converters.js via module.exports, you can retrieve this function by importing it with require() into any other js file. ”

1 Like