An introduction to the Use of Modularity in Node.js for Beginners

ยท

2 min read

nodeimage.jpeg In Client side Javascript, when you declare a variable or a function, it is added to the global scope. For example, when you define a function, it is added to the global scope and it is available via the window object.

var name = function() {
 //code goes in here
 }
 window.name();

In real world applications, we often split our Javascript code into multiple files in a code editor. When there are two files containing functions defined with same name, the other file will override the function definition of the former. Therefore, in order to build reliable and maintainable applications, avoid defining variables and functions in the global scope and use Modularity.

Modularity Defined

This is the process of creating small building blocks or modules where variables and functions are defined, where two functions or variables with the same name do not override another variable or function defined somewhere else.

Every file in a node application is considered a module, the variables and functions defined in that file or module are a scope to that file. In object-oriented programming term, they are private and are not available outside that module. If you want to use a variable or a function you find in a module, outside that module, you need to explicitly export it and make it public. Every node application has at least one module, which is called the main module

The module object contains properties, to see these properties, create a file in your code editor with nodejs installed. In the file type this console.log(module)

Screenshot from 2020-11-07 10.02.58.png Then open your terminal and run the file, the properties are listed.

Screenshot from 2020-11-07 10.07.41.png