Compile Ready
Module 13 · JavaScript Design Patterns

The Observer Pattern

Intermediate12m read16m practice28m total
Design PatternsObserverEventsState Changes

Introduction

The Observer Pattern lets a subject notify a list of dependent observers when its state changes. The subject owns the observer list, and observers usually implement an update() method.

This is one of the most common JavaScript interview patterns because it powers UI state updates, model-view relationships, custom event systems, and reactive programming ideas.

Why This Matters

Observer questions test more than syntax. A good implementation shows that you can manage subscriptions, preserve notification order, avoid mutation bugs during notification, and explain the coupling between a subject and its observers.

Theory

Core idea

The subject maintains a collection of observers. Observers subscribe to the subject. When the subject changes, it calls notify(data), and the subject pushes the update to every observer.

Roles

  • Subject: owns state, stores observers, exposes subscribe(), unsubscribe(), and notify().
  • Observer: object that reacts to updates, commonly by implementing update(value).

Notification order

Most simple implementations notify observers in subscription order. That detail matters in output-prediction interviews: if A subscribes before B, A is called before B.

Safe notification

Use a shallow copy of the observer list before iterating. That prevents a subscription or unsubscription during notification from corrupting the current traversal.

Coupling

Observer is somewhat coupled: the subject directly stores observer references and calls their update() method. That makes the relationship easy to trace, but subjects and observers know about each other more directly than in Publish/Subscribe.

Observer vs Pub/Sub preview

Observer has no separate broker; the subject itself manages observers. Pub/Sub introduces an intermediary event bus and topic strings, so publishers and subscribers do not need direct references to each other.

Visual Diagrams

Subject notifies observers
            subscribe
Observer A ------------+
                       |
Observer B ------------+--> Subject observer list
                       |
Observer C ------------+

Subject state changes
       |
       v
notify(value)
       |
       +--> A.update(value)
       +--> B.update(value)
       +--> C.update(value)

The subject directly owns the observer list and pushes updates to each observer.

Code Examples

Observer with update methods

The subject stores observer objects and calls update() when data changes.

Loading…

A stateful subject

Subjects often own state and notify observers only when that state changes.

Loading…

Playground

Loading editor…
Console

Press Run to execute the code and see output here.

Output Prediction

Predict the output #1

javascript
1function Subject() {
2 this.observers = [];
3}
4
5Subject.prototype.subscribe = function (observer) {
6 this.observers.push(observer);
7};
8
9Subject.prototype.notify = function (value) {
10 this.observers.forEach(function (observer) {
11 observer.update(value);
12 });
13};
14
15const subject = new Subject();
16
17subject.subscribe({
18 update: function (value) {
19 console.log('A:' + value);
20 }
21});
22
23subject.subscribe({
24 update: function (value) {
25 console.log('B:' + value);
26 }
27});
28
29subject.subscribe({
30 update: function (value) {
31 console.log('C:' + value);
32 }
33});
34
35subject.notify('deploy');

Coding Exercises

Implement an observable value

Medium

Implement createObservableValue(initialValue). It should return getValue(), setValue(nextValue), and subscribe(observer). Observers are objects with update(nextValue, previousValue). subscribe() should return an unsubscribe function. Notify observers only when the value actually changes.

Interview Questions

1Implement the Observer Pattern and explain the responsibilities of Subject and Observer.

The subject owns state and an observer collection. It exposes subscribe(observer), unsubscribe(observer) or an unsubscribe callback, and notify(data). Each observer implements update(data). When the subject changes, it iterates over observers and calls update(), usually in subscription order.

Asked at:MetaGoogleMicrosoft

Follow-ups

  • Why copy the observer list before notifying?
  • What happens if an observer unsubscribes itself during notification?
2What is the difference between Observer and Pub/Sub?

Observer has a direct relationship: the subject stores observer references and calls their update() methods. Pub/Sub introduces a broker or event bus; publishers publish messages to topic strings and subscribers listen to topics. Pub/Sub is more decoupled and supports many-to-many communication, but the flow can be harder to trace.

Quiz

1. In the Observer Pattern, who usually stores the list of observers?

2. Why is `observers.slice().forEach(...)` often used during notification?

Summary

  • Observer lets a subject push state changes to subscribed observers.
  • Observers commonly implement an `update()` method.
  • Simple implementations notify in subscription order.
  • The subject directly owns observer references, making Observer more coupled than Pub/Sub.

Cheat Sheet

Roles: Subject stores observers; Observer implements update().

Core methods: subscribe, unsubscribe, notify.

Order: usually subscription order.

Safety: notify over a copied list.

Observer vs Pub/Sub: Observer is direct subject-to-observer; Pub/Sub uses an event broker and topic strings.