JAVASCRIPT / CHAPTER 10
Closures and keyed state
IntermediateKeep state local and choose reliable key storage.
By the end of this chapter
- Trace independently created closures
- Use Map for arbitrary string keys
- Distinguish missing keys from stored falsey values
The idea
A closure is a function together with access to bindings from the scope where it was created. A factory can therefore create independent counters or caches without placing mutable variables in global scope. Follow the binding, not just the function text: two calls to the factory create separate environments, while repeated calls to one returned function share its environment.
Map is useful when keys arrive as data rather than as a fixed record shape. It supports explicit has, get, and set operations and preserves key insertion order. Checking has distinguishes an absent key from one whose stored value is undefined or zero. Keep the state private when callers should interact through operations rather than modify the underlying collection directly.
function counter() {
let value = 0;
return () => ++value;
}
const a = counter();
const b = counter();
console.log(a(), a(), b());1 2 1
Calls through a share one captured value. Creating b runs the factory again and creates a separate captured value.
Try it yourself
Create a counter by category using Map; each call should return the updated count for that category.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING