MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Singleton Pattern & Module Pattern0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
9.1Singleton Pattern & Module Pattern9.2Factory & Builder Patterns9.3Observer & Pub/Sub Pattern9.4Strategy & State Patterns9.5Proxy & Decorator Patterns
HomeTutorialsJavaScript for AdvancedSingleton Pattern & Module Pattern
Factory & Builder Patterns

Singleton Pattern & Module Pattern

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Design patterns provide battle-tested architectural blueprints for common software engineering challenges. The Singleton Pattern and the Module Pattern are foundational creational and structural patterns in JavaScript used for state centralization, resource pooling, and namespace encapsulation.


1. The Singleton Pattern

The Singleton Pattern restricts the instantiation of a class to one single instance across the entire application, providing a global point of access.

Modern Implementation: Class-Based with Instance Guard

1class DatabasePool {
2 static #instance = null;
3 
4 constructor(connectionUri) {
5 if (DatabasePool.#instance) {
6 // Return existing singleton instance!
7 return DatabasePool.#instance;
8 }
9 
10 this.connectionUri = connectionUri;
11 this.connections = [];
12 this.isConnected = true;
13 
14 // Cache the single instance
15 DatabasePool.#instance = this;
16 }
17 
18 static getInstance(uri = 'mongodb://localhost:27017/prod') {
19 if (!DatabasePool.#instance) {
20 DatabasePool.#instance = new DatabasePool(uri);
21 }
22 return DatabasePool.#instance;
23 }
24 
25 query(sql) {
26 return `Executing "${sql}" on pool ${this.connectionUri}`;
27 }
28}
29 
30// Verification:
31const pool1 = new DatabasePool('db1');
32const pool2 = new DatabasePool('db2'); // Ignored uri, returns pool1!
33 
34console.log(pool1 === pool2); // TRUE! Identical memory reference!

2. Singletons via ES Modules (Native Singleton)

Because ECMAScript Modules execute once and cache their exports, simply exporting an instantiated object makes it a native singleton with zero boilerplate:

1// LoggerService.js
2class Logger {
3 constructor() {
4 this.logs = [];
5 }
6 log(msg) { this.logs.push(msg); }
7}
8 
9// Export single instantiated instance:
10export const logger = Object.freeze(new Logger());

3. The Classic Module Pattern (Closure-Based)

Before native ES Modules, the Module Pattern used Immediately Invoked Function Expressions (IIFEs) and closures to simulate private state and expose a public API:

1const CartModule = (function () {
2 // Private variables and functions (inaccessible from outside!)
3 let items = [];
4 const taxRate = 0.08;
5 
6 function calculateTotal() {
7 const subtotal = items.reduce((sum, item) => sum + item.price, 0);
8 return subtotal * (1 + taxRate);
9 }
10 
11 // Public API returned to consumer
12 return {
13 addItem(product) {
14 items.push(product);
15 console.log(`Added ${product.name}`);
16 },
17 getItemCount() {
18 return items.length;
19 },
20 getTotal() {
21 return calculateTotal();
22 }
23 };
24})();
25 
26// Usage:
27CartModule.addItem({ name: 'Headphones', price: 100 });
28console.log(CartModule.getTotal()); // 108
29// console.log(CartModule.items); // undefined! (Truly private!)

4. Comparing the Patterns

FeatureSingleton PatternModule Pattern
Primary GoalGuarantee exactly one instance exists globallyEncapsulate private state and expose clean public API
InstantiationLazily or eagerly instantiated classTypically evaluated immediately via IIFE or ESM
Ideal ForDatabase pools, WebSocket connections, state storesUtility namespaces, service controllers, widgets

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the core guarantee of the Singleton Pattern?
Question 2
Why are ES Modules natural singletons in JavaScript?
Question 3
How did the traditional JavaScript Module Pattern achieve data privacy before ES2022 private fields?
Question 4
Why is Object.freeze() often called on singleton objects?
Question 5
What is a common testing criticism of the Singleton Pattern?
Next Lesson

Factory & Builder Patterns

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Pointer Events & Gesture HandlingFactory & Builder Patterns

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext