Course contentsShow
← JavaScript
Lesson 2106 of 2,72344. Reactive PatternsFree lesson

What Is the Observer Pattern?

Learn the core concept: subjects notify observers when state changes, enabling loose coupling between components.

What Is the Observer Pattern?

You'll learn: the fundamental idea behind one of JavaScript's most important reactive design patterns—where subjects notify observers when state changes.

The Core Idea

The Observer Pattern is a design pattern where an object (the subject) maintains a list of dependents (the observers) and automatically notifies them when its internal state changes. Instead of objects constantly checking whether something has changed, they subscribe to be notified when it happens.

Think of it like a newsletter subscription: you don't call the publisher every day asking "anything new?" Instead, you subscribe once, and they notify you whenever there's an update.

How It Works

The subject provides methods to:

  • Subscribe: add an observer to the notification list
  • Unsubscribe: remove an observer from the list
  • Notify: alert all observers when state changes

The observers implement an update method that the subject calls when notifying.

This creates loose coupling—the subject doesn't need to know what the observers do with the information, just that they want to be notified. Observers don't need to poll the subject; they passively wait for updates.

Why It Matters

The Observer Pattern enables reactive programming: components react to changes without tight dependencies. You'll see this pattern everywhere in JavaScript:

  • Event listeners are observers of DOM elements
  • State management libraries use observers to update UI components
  • Reactive data systems notify subscribers when data flows through

Key Takeaway: The Observer Pattern decouples components by having subjects maintain a list of observers and automatically notify them of state changes, enabling reactive, event-driven architectures without tight coupling between objects.