JavaScript Modules

JavaScript modules are an excellent implementation of closures. Modules are small units of independent, reusable code that serve as building blocks for creating complex JavaScript applications. They allow developers to define private and public members separately, making them a highly desired design pattern in JavaScript.

Modules can be compared to classes in other object-oriented programming languages. Although JavaScript introduced the class keyword in ES2015, it remains a classless programming language, as ES2015 classes are essentially special functions.

Example:

javascript
<script>
    // This is a Rectangle Module.
    function Rectangle() {
        var length, width;
    
        function create(l, w) {
            length = l;
            width = w;
        }
    
        function getArea() {
            return (length * width);
        }
    
        function getPerimeter() {
            return (2 * (length + width));
        }
    
        // This is the object to consist public members.
        // The rest are private members.
        var publicAPI = {
            create: create,
            getArea: getArea,
            getPerimeter: getPerimeter
        };
    
        // To be returned upon creation of a new instance.
        return publicAPI;
    }
    
    // Create a Rectangle module instance
    var myRect = Rectangle();
    myRect.create(5, 4);
    console.log("Area: " + myRect.getArea());
    console.log("Perimeter: " + myRect.getPerimeter());
</script>

Output:

Area: 20
Perimeter: 18

The Rectangle() function acts as an outer scope that contains the necessary variables (length, width) and functions (setDimensions(), getArea()). These are private details of the Rectangle module, inaccessible from outside. The public API, as its name suggests, is an object with three functional members, returned upon the completion of the Rectangle function execution. Using the API methods, we can set dimensions and get the values for the area and perimeter of the rectangle.

Key Points

  1. Private Scope: The Rectangle function encloses private variables (length, width) and functions. These cannot be accessed or modified from outside the module.
  2. Public API: The returned object contains public methods (setDimensions, getArea) that interact with the private scope.
  3. No new Keyword: Unlike classes in other OOP languages, the Rectangle function is not instantiated with new. It is simply called as a function. Using new would be inappropriate and waste resources.
  4. Closure: The member functions have closure over the length and width variables, meaning they can access these even after the Rectangle function has finished executing.

Note: As we mentioned earlier that modules are the closest concepts of Classes in any other OOP language, many developers might feel like using the ‘new’ keyword while creating a new instance of the Rectangle Module. Rectangle() is just a function, not a proper class to be instantiated, so it’s just called normally. Using new would be inappropriate and actually waste resources. Executing Rectangle() creates an instance of the Rectangle module and a whole new scope is created and allocated to the function, and therefore a new instance of the member of the functions was generated, as we assigned it to a variable, now the variable had the reference to the allowed public API members.

Hence, we can see that running the Rectangle() method creates a new instance entirely separate from any other previous one. All the member functions have a closure over the length and width, which means that these functions can access them even after the Rectangle() function execution is finished. That sums up how Modules work in JavaScript. We will uncover more interesting topics on JavaScript and make relevant projects to hone our newly learned skills soon.

JavaScript Modules

The article on closures in JavaScript, we learned that closures are one of the most important yet misunderstood concepts in JavaScript. A closure allows a child function to retain the environment of its parent scope even after the parent function has executed. In other words, it remembers or recreates the scope and its members that have already been executed.

Similar Reads

JavaScript Modules

JavaScript modules are an excellent implementation of closures. Modules are small units of independent, reusable code that serve as building blocks for creating complex JavaScript applications. They allow developers to define private and public members separately, making them a highly desired design pattern in JavaScript....

Conclusion

Closures and modules are powerful tools in JavaScript. Modules, in particular, provide a structured way to organize code, making it more maintainable and reusable. By understanding and utilizing these concepts, you can write more efficient and robust JavaScript applications....

Contact Us