1. Home
  2. Explore
  3. Computer Science
  4. JavaScript OOP & Design Patterns

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

JavaScript OOP & Design Patterns

Module Design Pattern in JavaScript

Introduction to Design Patterns and the Course Context

This advanced JavaScript course targets developers who struggle to fully grasp the benefits and complexity of object‑oriented programming. It is especially relevant for those who have read about design patterns but remain unsure where to apply them, or who work with modern frameworks and find the architecture overwhelming. Even developers who rely on AI‑assisted coding need to understand what the generated code actually does. The course uses real‑life web‑application examples — no cars, pizzas, or animals — and covers ten of the most useful design patterns.

The instructor, Dalibor, has nearly 20 years of experience building over 200 products, including single‑page sites, e‑commerce platforms, mobile apps, and custom CMS frameworks. When he started actively using design patterns, his code improved, he began understanding complex functionality in frameworks, and his career advanced significantly. Most importantly, he gained confidence in his solutions instead of fearing errors.

The Module Pattern: Core Concepts

Module Design Pattern – A way to organize and encapsulate code into self‑contained units (modules) so that the code from one module does not interfere with code from another module.

In JavaScript, almost everything is an object, yet writing flexible and maintainable code with effective objects is not trivial. Design patterns are proven recipes for solving common problems in object‑oriented code. The module pattern is essential for any serious JavaScript application because it provides:

  • Namespace management – Avoids cluttering the global scope by grouping related code under a single container (namespace). This prevents naming conflicts between different parts of the application.

  • Reusability – Modules can be copied and used in other applications with little or no modification.

  • Code structure – Each module resides in its own file, making it easy to locate and work on specific functionality. Modules can be loaded from HTML or imported into other JavaScript files.

  • Scalability – Well‑structured files make it easier for an application to grow because new modules can be added without bloating existing files.

  • Encapsulation and access control – Only the parts of a module that are explicitly exported are accessible from the outside. Private functions and data remain hidden, preventing accidental interference.

Disadvantages include:

  • Learning curve – Developers unfamiliar with the concept may find it unnatural or overcomplicated.

  • Risk of overhead – Creating too many tiny modules for simple tasks can make maintenance harder than using a plain function.

  • Circular dependency – Two or more modules depending on each other cause runtime issues that are notoriously difficult to debug.

The Problem the Module Pattern Solves

Consider a simplified e‑commerce application where users place orders and then shipping is calculated. The code contains functions like create, process, and update for orders. Soon the same operations are needed for shipping. Simply adding another process and update function causes a syntax error because the names are already taken.

Naive solution: Rename functions to processShipping, updateShipping, createOrder, processOrder, etc. This works for a small application, but as the project grows — adding users, products, admin functions, guest accounts — the developer ends up with dozens of similar‑sounding names (createUserAdmin, createGuestUser, createUserEditor…). This approach is unsustainable, makes autocomplete unusable, and creates confusion among team members.

Object literals provide some organization by grouping methods under a single object (e.g., orderManager). However, this still suffers from:

  • No true encapsulation – All properties and methods are publicly accessible. Accidentally overwriting internal data from outside the object can corrupt the entire application.

  • Everything is exposed – Internal helper functions are visible to consumers, cluttering the interface and risking misuse.

  • Single file limitation – The entire object must stay in one file, which grows unmanageable as the application scales.

How the Module Pattern Solves These Problems

The module pattern divides code into separate files, each exporting only the necessary functionality. This solves the naming problem by allowing the same method name (e.g., create, update) to exist in different modules without conflict — each module is a separate namespace.

Example with ES6 modules:

  • Create a file order.js that exports an object orderModule containing methods create, process, and update.

  • Create a file shipping.js that exports shippingModule containing methods process and update.

  • In the main application file (app.js), import both modules:

import { orderModule } from './order.js';
import { shippingModule } from './shipping.js';

orderModule.create(…);
orderModule.process(…);
orderModule.update(…);
shippingModule.process(…);
shippingModule.update(…);

Results achieved:

  • Namespace management – create inside orderModule is distinct from any create in another module. The application can grow without method name conflicts.

  • Encapsulation – All order‑related logic is contained in order.js. Private data (e.g., an internal reference to order data) can be declared outside the exported object and remains inaccessible from the outside unless explicitly exported.

// order.js
const orderData = { customer: 'John', items: [] }; // private

export const orderModule = {
  getOrderData() {
    return { ...orderData }; // return a copy to protect the original
  },
  create() { /* ... */ },
  process() { /* ... */ },
  update() { /* ... */ }
};
  • Access control – Functions or variables that are not exported (like cleanUp()) cause an error if another file tries to use them. The IDE will also not suggest them, making the public API clear.

  • Reusability – A module file can be copied to another project and imported there with minimal adjustments.

  • Scalability – New modules are simply new files. They are not loaded until imported, keeping the application performant.

Circular Dependency

Circular dependency occurs when module A depends on module B, and module B depends directly or indirectly on module A, forming a loop.

Although ES6 modules handle this better than older module systems, it is not completely eliminated. If a circular dependency arises, introduce a mediator module that imports both conflicting modules and orchestrates their interaction. Tools like Webpack and RequireJS also offer assistance.

Case Studies in Real‑World Frameworks

Strapi (Headless CMS)

Strapi is an open‑source CMS that provides only a backend. It uses modules extensively, often in TypeScript. Common patterns include importing React components (like Button) and exporting default configurations that the main application bootstraps. Users can reuse these modules and customize settings (e.g., menu, logo) in theme files without editing the core JavaScript directly.

Decap (CMS with Frontend)

Decap stores content statically in a Git repository (no database). Its Node.js source code uses require() to import modules. For example, in publish.js, it imports various modules; in a Webpack configuration, it imports plugins. This demonstrates that the module pattern is equally valid on the server side.

React

React relies on the module pattern for nearly everything, including components. Each component is effectively a module. The vast number of files and folders would be impossible to manage without splitting them into modules. For instance, dangerfile.js imports many other components and modules, showing how the pattern enables organization at scale.

Summary of the Module Pattern

Purpose: Organize and structure components of a system to manage complexity in larger applications.

Advantages:

  • Encapsulation – Separates concerns by grouping relevant functionality in one file.

  • Namespace management – Allows shorter, relevant method names and avoids conflicts between modules that may use the same names.

  • Scalability – Easy to add new code without files becoming gigantic.

  • Reusability – Modules can be copied to new applications.

  • Access control – Private members stay protected; only exported members form the public API.

Disadvantages / Dangers:

  • Circular dependency – Still possible with ES6 modules; needs awareness and mitigation.

  • Over‑complexity – Creating modules for trivial functionality adds unnecessary overhead. Use simpler solutions when they suffice.

When to use: If an application is expected to grow or will be worked on by multiple developers, adopting modules (or a similar modular approach) from the start is wise.

Skill Builder Exercises

To truly learn (not just understand), practice is essential. The course provides downloadable source code with tasks. One example: four functions — two for admin user (createAdminUser, updateAdminUser) and two for product (createProduct, updateProduct). The task is to split them into two files (modules), import them, and call them with proper namespace.

A possible solution:

  • userAdmin.js: export create and update directly.

  • productAdmin.js: export create and update directly.

  • In the main file, import both modules and either assign them to objects (e.g., userAdmin) or import with aliases to avoid naming collisions.

import * as userAdmin from './userAdmin.js';
import * as productAdmin from './productAdmin.js';

userAdmin.create(…);
userAdmin.update(…);
productAdmin.create(…);
productAdmin.update(…);

The key is to attempt the exercise without searching for answers, then compare with the provided solution or share in the community. Doing — not just watching — builds lasting knowledge.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent