Javascript Patterns in ES6

Akash Pal
Frontend Weekly
Published in
2 min readMay 15, 2024

--

1. Module Pattern

️ℹ️ Splits large file into multiple smaller reusable pieces.

Html

  • adding the type="module" attribute to the script tags

Node

  • Using the .mjs extension
  • Adding "type": "module" to your package.json
Module Pattern

Encapsulation — values within a module are private by default

Reusability — modules can be reused

2. Singelton Pattern

️ℹ️ ️️Allows class to have single instance only, which cannot be modified and is available globally.

Singleton Pattern using Class
Singleton Pattern using Object

✅ Memory — Reduced memory, setup for just one instance and reused

❌ Un-necessary — ES2015 Modules are singletons by default.

❌ Dependency Hiding — importing module may or may not be singleton

❌Global Scope Pollution — same as global variable can result in over-writing singleton value

3. Proxy Pattern

️ℹ️ Utilises proxy to intercept and control interaction stoa target object

Proxy Pattern
Proxy Pattern using Reflect

✅ Control — adds functionality when interacting with objects

❌ Long handler execution — performance issues due to executing handles on every object

4. Observer Pattern

️ℹ️ Use observables to notify subscribers when an event occurs

✅ Separation of Concerns — observers can be decoupled from the observable object any time.

❌ Decreased performance — too many subscribers or complex observer handling can result in delay in notifying all subscribers

5. Factory Pattern

️ℹ️ Use a factory function in order to create objects

Factory Pattern

✅ DRY — multiple objects with same properties can be created

❌ Not really a pattern — function that returns an object

6. Prototype Pattern

️ℹ️ Share properties among many objects of the same type

Prototype Pattern

✅ Memory efficient — common methods and properties moved to prototype.

❌ Readability — extending classes multiple times may result in difficulty in tracing the method and properties origin.

--

--