Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.2 — Design Patterns in JavaScript
JavaScript · Example 1 of 3 ES2022+

Module pattern and an observer with unsubscribe

counter.count is undefined: the variable is private to the closure. Emitter {} looks empty because #private fields are not ordinary properties.

Design patterns are named, proven shapes for common code problems; in JavaScript the everyday ones are the module (private state), observer and pub/sub (notify listeners), factory (build the right object), singleton (one shared instance) and strategy (swap the algorithm).

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a factory function createAccount(owner) that keeps balance private and returns deposit, withdraw (refusing to go below 0 by throwing) and getBalance.

02

Add a once(event, fn) method to the Emitter class from the first example.

03

Replace this switch with a strategy object: function discount(type, price) { switch (type) { case "student": return price * 0.5; case "senior": return price * 0.7; default: return price; } }.

Explain it without notes

01

How do you get private state in JavaScript? Give three ways.

02

What is the difference between the observer pattern and pub/sub?

03

Why can a singleton be a problem, and what does JavaScript give you instead?

04

Explain the strategy pattern with an example from the standard library.

Module pattern and an observer with unsubscribe ES2022+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

2 undefined
A saw 10
B saw 10
B saw 12
Emitter {}