CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❤️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

👀 Observer Pattern — React to Change Automatically

Notifies observers automatically when a subject changes state. Use for event handling, UI state changes, and one-to-many update scenarios.

Use this guide as a quick-reference for interviews or design discussions. -- 1️⃣ Core Idea The Observer Pattern (also known as the Pub/Sub Pattern ) is a behavioral design pattern in which a subject (publisher) maintains a list of observers (subscribers) and notifies them automatically whenever a state change or event occurs. This pattern promotes loose coupling between the subject and the observers, facilitating clean, modular design — a fundamental principle of event-driven programming. -- 2️⃣ JavaScript & Event-Driven Programming JavaScript is one of the most event-driven programming languages. We frequently use the Observer Pattern via event listeners : ✅ The browser’s event system is a natural example of the observer pattern in action. -- 3️⃣ Basic Implementation 3.1 Simple Observer System Output: -- 4️⃣ Advanced Version: Multi-Mode Event Hub Inspired by a Coursera interview, here's an advanced Observer implementation supporting: Sample Test -- 5️⃣ Observer vs Pub-Sub Observer Subject holds observer references Direct method call MVC apps, local state updates -- 6️⃣ Pros & Cons ⚠️ Drawbacks May cause memory leaks (unremoved observers) Supports dynamic notification Complex state sync in larger apps | -- 7️⃣ Interview Q&A Q1: What is the Observer Pattern? A: It’s a behavioral pattern where an object (subject) notifies a list of observers when a change in state occurs. Q2: Difference between Observer and Pub/Sub? A: In Observer, the subject knows the observers directly. In Pub/Sub, they are decoupled via a message broker or event bus. Q3: How does JavaScript use the Observer Pattern? A: Through event listeners (, ), state libraries like Redux, and libraries like RxJS. Q4: When is Observer not a good fit? A: In highly decoupled systems where components should not know about each other; use Pub/Sub instead. Q5: How do you prevent memory leaks with observers? A: Always observers when they’re no longer needed, especially in component unmounts. Q6: Can we use Observer Pattern with Promises? A: Yes, using to resolve a Promise when an event is published, allowing one-time async handling. Q7: What's the real-world analogy for Observer Pattern? A: A YouTube channel (subject) where subscribers (observers) get notified when a new video is published. -- 🔚 Key Takeaways Observer Pattern enables reactive communication between objects. Ideal when one-to-many updates are required, like UI refreshes, live feeds , or modular plugins . JavaScript embraces this pattern heavily through DOM events , custom listeners , and async flows . Master this pattern to design flexible , scalable , and responsive systems. 🧠🔄 -- <!-quiz-start --Q1: What is the key difference between the Observer Pattern and the Pub/Sub Pattern? [ ] They are exactly the same [x] In Observer, the subject knows observers directly; in Pub/Sub, they are decoupled via an event bus [ ] Pub/Sub only works with async code [ ] Observer cannot have multiple subscribers Q2: How can you prevent memory leaks when using the Observer Pattern? [ ] Use more observers [ ] Never unsubscribe [x] Always unsubscribe observers when they are no longer needed [ ] Use global variables for all observers Q3: Which JavaScript feature is a natural example of the Observer Pattern in action? [ ] Promises [ ] Closures [x] DOM event listeners (addEventListener) [ ] Template literals <!-quiz-end --
Browser & PatternsDesign Patterns
🎭 The Facade Pattern in JavaScript – Simplifying Complex Systems
medium
🏭 The Factory Pattern in JavaScript – A Practical Guide
medium
📘 Most Important Design Patterns in JavaScript
medium
🧠 When to Use Which Design Pattern in JavaScript
medium
📦 The Module Pattern in JavaScript — A Deep Dive
medium
🧭 MVC (Model‑View‑Controller) — A Front‑End Deep Dive
medium
👀 Observer Pattern — React to Change Automatically
medium
🔒 Singleton — One Instance to Rule Them All
medium
7 of 8
LibraryBrowser & PatternsDesign Patterns9 of 14

👀 Observer Pattern — React to Change Automatically

generaldesign-patternsmedium

Use this guide as a quick-reference for interviews or design discussions.


1️⃣ Core Idea

The Observer Pattern (also known as the Pub/Sub Pattern ) is a behavioral design pattern in which a subject (publisher) maintains a list of observers (subscribers) and notifies them automatically whenever a state change or event occurs.

+--------------+       update()       +--------------+
|  Subject 🔔  | -------------------▶ | Observer 👁  |
| (Notifier)  | ◀------------------- | (Listener)   |
+--------------+       subscribe()    +--------------+

This pattern promotes loose coupling between the subject and the observers, facilitating clean, modular design — a fundamental principle of event-driven programming.


2️⃣ JavaScript & Event-Driven Programming

JavaScript is one of the most event-driven programming languages. We frequently use the Observer Pattern via event listeners :

const button = document.querySelector("#myBtn");
const handleClick = (e) => console.log(e.clientX, e.clientY);

button.addEventListener("click", handleClick);
// Later:
button.removeEventListener("click", handleClick);

✅ The browser’s event system is a natural example of the observer pattern in action.


3️⃣ Basic Implementation

3.1 Simple Observer System

const Move = function(){
  this.handlers = [];

  this.subscribe = function (fn) {
    this.handlers.push(fn);
  };

  this.unsubscribe = function (fn) {
    this.handlers = this.handlers.filter((item) => item !== fn);
  };

  this.fire = function (o, thisObj) {
    const scope = thisObj || window;
    this.handlers.forEach((item) => {
      item.call(scope, o);
    });
  }
}

const moveHandler = (item) => console.log("fired: " + item);
const moveHandler2 = (item) => console.log("Moved: " + item);

const move = new Move();

move.subscribe(moveHandler);
move.fire('event #1');
move.unsubscribe(moveHandler);
move.fire('event #2');
move.subscribe(moveHandler);
move.subscribe(moveHandler2);
move.fire('event #3');

Output:

fired: event #1
fired: event #3
Moved: event #3

4️⃣ Advanced Version: Multi-Mode Event Hub

Inspired by a Coursera interview, here's an advanced Observer implementation supporting:

  • subscribe()
  • subscribeOnce()
  • subscribeOnceAsync()
  • publish()
  • publishAll()
function Events() {
  this.subscriptionList = new Map();
  this.subscribeOnceList = new Map();
  this.subscribeOnceAsyncList = new Map();

  this.subscribe = function (name, callback) {
    if (!this.subscriptionList.has(name)) {
      this.subscriptionList.set(name, [callback]);
    } else {
      const existing = this.subscriptionList.get(name);
      this.subscriptionList.set(name, [...existing, callback]);
    }
    return {
      remove: () => {
        const existing = this.subscriptionList.get(name);
        const filtered = existing.filter(e => e !== callback);
        this.subscriptionList.set(name, filtered);
      }
    };
  };

  this.subscribeOnce = function (name, callback) {
    if (!this.subscribeOnceList.has(name)) {
      this.subscribeOnceList.set(name, [callback]);
    } else {
      const existing = this.subscribeOnceList.get(name);
      this.subscribeOnceList.set(name, [...existing, callback]);
    }
  };

  this.subscribeOnceAsync = async function (name) {
    return new Promise((resolve) => {
      if (!this.subscribeOnceAsyncList.has(name)) {
        this.subscribeOnceAsyncList.set(name, [resolve]);
      } else {
        const existing = this.subscribeOnceAsyncList.get(name);
        this.subscribeOnceAsyncList.set(name, [...existing, resolve]);
      }
    });
  };

  this.publish = function (name, data) {
    const callbacks = this.subscriptionList.get(name) || [];
    callbacks.forEach((e) => e(data));

    const onceCallbacks = this.subscribeOnceList.get(name) || [];
    onceCallbacks.forEach((e) => e(data));
    this.subscribeOnceList.set(name, []);

    const asyncOnceCallbacks = this.subscribeOnceAsyncList.get(name) || [];
    asyncOnceCallbacks.forEach((e) => e(data));
    this.subscribeOnceAsyncList.set(name, []);
  };

  this.publishAll = function (data) {
    for (let [_, callbacks] of this.subscriptionList.entries()) {
      callbacks.forEach(e => e(data));
    }
  };
}

Sample Test

const events = new Events();

const sub1 = events.subscribe("new-user", (payload) => console.log(`Q1 News: ${payload}`));
events.publish("new-user", "Jhon");

const sub2 = events.subscribe("new-user", (payload) => console.log(`Q2 News: ${payload}`));
events.publish("new-user", "Doe");

sub1.remove();
events.publish("new-user", "Foo");

events.publishAll("FooBar");

events.subscribeOnce("new-user", (payload) => console.log(`Once: ${payload}`));
events.publish("new-user", "Foo Once");
events.publish("new-user", "Foo Twice");

events.subscribeOnceAsync("new-user").then(payload => console.log(`Once Async: ${payload}`));
events.publish("new-user", "Foo Once Async");

5️⃣ Observer vs Pub-Sub

FeatureObserverPub-Sub
Direct linkSubject holds observer referencesDecoupled via channels/topics
Notification triggerDirect method callBroadcast via event bus or channel
Common inMVC apps, local state updatesMicroservices, cross-app communication

6️⃣ Pros & Cons

✅ Advantages⚠️ Drawbacks
Loose coupling, modularityMay cause memory leaks (unremoved observers)
Supports dynamic notificationCan cause performance issues with many subs
Easy integration in event systemsComplex state sync in larger apps

7️⃣ Interview Q&A

Q1: What is the Observer Pattern?

A: It’s a behavioral pattern where an object (subject) notifies a list of observers when a change in state occurs.

Q2: Difference between Observer and Pub/Sub?

A: In Observer, the subject knows the observers directly. In Pub/Sub, they are decoupled via a message broker or event bus.

Q3: How does JavaScript use the Observer Pattern?

A: Through event listeners (addEventListener, onClick), state libraries like Redux, and libraries like RxJS.

Q4: When is Observer not a good fit?

A: In highly decoupled systems where components should not know about each other; use Pub/Sub instead.

Q5: How do you prevent memory leaks with observers?

A: Always unsubscribe() observers when they’re no longer needed, especially in component unmounts.

Q6: Can we use Observer Pattern with Promises?

A: Yes, using subscribeOnceAsync() to resolve a Promise when an event is published, allowing one-time async handling.

Q7: What's the real-world analogy for Observer Pattern?

A: A YouTube channel (subject) where subscribers (observers) get notified when a new video is published.


🔚 Key Takeaways

  • Observer Pattern enables reactive communication between objects.
  • Ideal when one-to-many updates are required, like UI refreshes, live feeds , or modular plugins .
  • JavaScript embraces this pattern heavily through DOM events , custom listeners , and async flows .

Master this pattern to design flexible , scalable , and responsive systems. 🧠🔄


Quick Quiz

Test your understanding with 3 quick questions

Q1What is the key difference between the Observer Pattern and the Pub/Sub Pattern?
Q2How can you prevent memory leaks when using the Observer Pattern?
Q3Which JavaScript feature is a natural example of the Observer Pattern in action?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❤️ by Tushar Khanna