Skip to main content

Mediator Pattern in JavaScript (Live Playground)

The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. This pattern uses a mediator object to handle interactions between various components, which helps to reduce dependencies between them. In this tutorial, we'll explore the Mediator pattern in JavaScript, including its use cases, implementation, and benefits.

Why Use the Mediator Pattern?

The Mediator pattern is useful when you want to:

  1. Reduce dependencies between objects, promoting loose coupling.
  2. Centralize communication between components.
  3. Simplify the maintenance and evolution of a system by isolating how objects interact.

Implementing the Mediator Pattern in JavaScript

Here's an example of how to implement the Mediator pattern using JavaScript classes:

// Mediator interface
class Mediator {
send(message, sender) {}

// Concrete mediator
class ChatRoomMediator extends Mediator {
constructor() {
this.users = {};

addUser(user) {
this.users[] = user;

send(message, sender) {
for (const userName in this.users) {
if (userName !== {
this.users[userName].receive(message, sender);

// Colleague interface
class Colleague {
setMediator(mediator) {}
send(message) {}
receive(message, sender) {}

// Concrete colleague
class User extends Colleague {
constructor(name) {
super(); = name;

setMediator(mediator) {
this.mediator = mediator;

send(message) {
this.mediator.send(message, this);

receive(message, sender) {
console.log(`${} to ${}: ${message}`);

// Client code
const chatRoom = new ChatRoomMediator();
const alice = new User('Alice');
const bob = new User('Bob');


alice.send('Hello, Bob!');
bob.send('Hi, Alice!');

In this example, the Mediator class represents the mediator interface, and ChatRoomMediator is a concrete mediator class. The Colleague class represents the colleague interface, and User is a concrete colleague class. The client code creates a chat room (mediator) and users (colleagues) that communicate through the mediator.

Live Playground, Try it Yourself

Benefits of the Mediator Pattern

Implementing the Mediator pattern in your JavaScript projects offers several benefits:

  1. Loose Coupling: The Mediator pattern promotes loose coupling between objects by centralizing communication, making your code more maintainable and easier to modify.
  2. Simplicity: The Mediator pattern simplifies interactions between objects, making your code more readable and easier to understand.
  3. Reusability: The Mediator pattern allows you to reuse components in different contexts, as they are not tightly coupled to each other.


In summary, the Mediator pattern is a valuable tool in JavaScript development that can help you create maintainable, decoupled code. By understanding and implementing this pattern, you can enhance your web development skills and create more robust applications.