Full answer
Both are behavioral patterns that decouple parts of a program.
Observer: a subject keeps a list of observers and calls them when something changes. The subject does not know what the observers do. Examples are DOM events (addEventListener), Node's EventEmitter, store subscriptions in UI libraries, and MutationObserver. A good implementation has:
subscribe(observer)that returns anunsubscribefunction, so cleanup is easy and no one needs a reference to the original function.notify(data)that iterates over a copy of the observer list, so observers can unsubscribe while being called.- Error isolation, so one failing observer does not stop the rest.
- No memory leaks: observers that are never removed keep the subject, and everything they capture, alive. This is a classic leak with long-lived subjects.
Observer differs from publish and subscribe: in observer, observers subscribe directly to the subject; in pub/sub, a broker sits between publishers and subscribers who share only topic names.
Strategy: define a family of algorithms with the same signature, put each in its own unit, and choose one at runtime. In class-based languages you create an interface and several classes. In JavaScript, functions are first-class values, so a strategy is usually a function, and the context stores it or receives it as an argument. A map from names to functions replaces a growing if or switch chain: const strategies = { flat, percent, bulk }. Examples: sort comparators, validation rules, pricing and shipping rules, retry policies, and formatting.
Benefits: you add a new behavior without editing the code that uses it (open and closed principle), and each strategy is easy to test alone. Cost: more units to name and find, and for two simple branches a plain if is clearer.
Together they appear often: a settings object holds a strategy and notifies observers when the strategy changes.
// Observer
class Store {
#state;
#observers = new Set();
constructor(initial) {
this.#state = initial;
}
get state() {
return this.#state;
}
subscribe(observer) {
this.#observers.add(observer);
return () => this.#observers.delete(observer);
}
set(change) {
const previous = this.#state;
this.#state = { ...previous, ...change };
for (const observer of [...this.#observers]) {
try {
observer(this.#state, previous);
} catch (error) {
console.log('observer failed:', error.message);
}
}
}
get observerCount() {
return this.#observers.size;
}
}
const store = new Store({ theme: 'light', user: null });
const seen = [];
const stopLogging = store.subscribe((state, previous) => seen.push(`log: ${previous.theme} -> ${state.theme}`));
store.subscribe(() => { throw new Error('bad observer'); });
const stopOnce = store.subscribe(() => { seen.push('once'); stopOnce(); });
store.set({ theme: 'dark' });
store.set({ theme: 'light' });
stopLogging();
store.set({ theme: 'dark' });
console.log(seen, 'observers left:', store.observerCount);
// Strategy: plain functions chosen by name
const discounts = {
none: (price) => price,
percent: (price, value) => price * (1 - value / 100),
flat: (price, value) => Math.max(0, price - value),
bulk: (price, value, quantity) => (quantity >= 10 ? price * 0.9 : price),
};
function totalPrice({ price, quantity, strategy = 'none', value = 0 }) {
const apply = discounts[strategy];
if (!apply) throw new RangeError('Unknown discount: ' + strategy);
return Number((apply(price, value, quantity) * quantity).toFixed(2));
}
console.log(totalPrice({ price: 50, quantity: 2 }));
console.log(totalPrice({ price: 50, quantity: 2, strategy: 'percent', value: 20 }));
console.log(totalPrice({ price: 50, quantity: 2, strategy: 'flat', value: 60 }));
console.log(totalPrice({ price: 50, quantity: 10, strategy: 'bulk' }));
try {
totalPrice({ price: 1, quantity: 1, strategy: 'coupon' });
} catch (error) {
console.log(error.message);
}
// Strategies as comparators
const people = [{ name: 'Chen', age: 42 }, { name: 'Asha', age: 31 }, { name: 'Ben', age: 25 }];
const sortBy = { name: (a, b) => a.name.localeCompare(b.name), age: (a, b) => a.age - b.age };
console.log(people.toSorted(sortBy.name).map((p) => p.name), people.toSorted(sortBy.age).map((p) => p.name));Run with Node.js v24.22.1 as js-144.js; two runs gave identical output. Output: observer failed: bad observer observer failed: bad observer observer failed: bad observer [ 'log: light -> dark', 'once', 'log: dark -> light' ] observers left: 1 100 80 0 450 Unknown discount: coupon [ 'Asha', 'Ben', 'Chen' ] [ 'Ben', 'Asha', 'Chen' ]
Key points
- Observer: a subject notifies subscribed observers of changes without knowing them; subscribe returns an unsubscribe function.
- Iterate over a copy, isolate errors, and remove observers to avoid leaks.
- Pub/sub adds a broker between publishers and subscribers; observer connects them directly.
- Strategy: interchangeable algorithms chosen at runtime; in JavaScript usually plain functions.
- A map of strategies replaces long conditionals; use plain if for two simple cases.
Common mistakes
- Never unsubscribing observers from long-lived subjects, which leaks memory.
- Iterating the live observer collection while observers remove themselves.
- Letting one throwing observer stop the others.
- Building a class hierarchy for strategies when functions are enough.
Follow-ups
- How is the observer pattern different from publish and subscribe?
- When is a plain if statement better than the strategy pattern?
- How would you combine strategy with dependency injection in tests?
Tips
- Show that subscribe returns an unsubscribe function.
- Say that in JavaScript a strategy is often just a function.
- Name the leak risk of observers.