There are crucial reasons to use JS modules such as Maintainability, Namespacing and Reusability, among others benefits.
I consider the hello greetings as a good start to understand how modules work. Write a module called hello.js to print a message that define the beginning of the hello.js module and to export a greeting by writing the reserved words module.exports. Then write a file called index.js to invoke the module required with its path. It can be a relative path as it is shown:Improving our hello.js module, it can accept any name to make a greeting:Names are accepted even though a number would have been instead of “Tux”. A common JS module validates information by checking the type of the parameter in a function. It can be written in the same hello.js file as follow:We are defining two modules in the hello.js file, one to print the greeting and the other module to validate the type of the name entered, in case we set the name as number 200, a message of “Please enter a valid name” is shown inmediately.
And because writing in all caps is considered to be shouting, we can create another module to convert the name in the message all in lowercase if the input was written in uppercase. Another file “lower.js” is used this time to export it into the index.js file: