Skip to main content

Module Design Pattern

Structural: Module Pattern

Can you explain the Module design pattern?

View Answer:
Interview Response: Another popular JavaScript design pattern for keeping our code tidy, segregated, and organized is the Module Pattern. A module is a standalone code that may modify objects without impacting other components. In JavaScript does not support the concept of an access modifier, the aid of the module in mimicking the behavior of private/public access, thereby ensures encapsulation.

Code Example: Modern Implementation

// The Module Pattern

// ES2015+ keywords used: import, export, let, const

let counter = 0;

const testModule = {
incrementCounter() {
return counter++;
resetCounter() {
console.log(`counter value prior to reset: ${counter}`);
counter = 0;

// Default export module, without name
export default testModule;

// Usage:

// Import module from path
import testModule from './testModule';

// Increment our counter

// Check the counter value and reset
// Outputs: counter value prior to reset: 1