Describe the JS module design pattern

Technology CommunityCategory: JavaScriptDescribe the JS module design pattern
VietMX Staff asked 3 years ago

JavaScript modules are the most prevalently used design patterns for keeping particular pieces of code independent of other components. This provides loose coupling to support well-structured code.

Modules should be Immediately-Invoked-Function-Expressions (IIFE) to allow for private scopes – that is, a closure that protect variables and methods (however, it will return an object instead of a function). This is what it looks like:

(function() {
    // declare private variables and/or functions
    return {
      // declare public variables and/or functions
    }
})();

Here we instantiate the private variables and/or functions before returning our object that we want to return. Code outside of our closure is unable to access these private variables since it is not in the same scope.