Sub topic 12
Practical Patterns: Validation, Logging, Defaults, and Hidden Properties
This chapter assumes you already know the get, set, has, deleteProperty, and ownKeys traps, and that you forward to the target with the matching Reflect method and the receiver. Here those pieces become reusable wrappers. Each wrapper is a small factory function: it takes a target and returns a proxy. Because a proxy is itself an object, it can be the target of another proxy, so you can stack these wrappers.
Validation: Reject Bad Writes
A validation proxy checks a value in the set trap before it reaches the target. Rules live in a plain object that maps property names to predicate functions.
function withValidation(target, rules) {
return new Proxy(target, {
set(target, prop, value, receiver) {
if (Object.hasOwn(rules, prop) && !rules[prop](value)) {
throw new TypeError(`Invalid value for ${String(prop)}: ${value}`);
}
return Reflect.set(target, prop, value, receiver);
}
});
}
const product = withValidation({}, {
price: (v) => typeof v === 'number' && v >= 0,
name: (v) => typeof v === 'string' && v.length > 0
});
product.price = 9.99; // stored
product.name = 'Lamp'; // stored
try {
product.price = -5;
} catch (err) {
console.log(err.message); // "Invalid value for price: -5"
}Object.hasOwn matters here. A plain rules[prop] lookup would find inherited members such as toString and treat them as rules.
Logging: Record Every Access
A logging proxy writes a line for each operation and then forwards it unchanged. The logger is passed in as an argument, so tests can capture its output.
function withLogging(target, log = console.log) {
return new Proxy(target, {
get(target, prop, receiver) {
log(`get ${String(prop)}`);
return Reflect.get(target, prop, receiver);
},
set(target, prop, value, receiver) {
log(`set ${String(prop)} = ${JSON.stringify(value)}`);
return Reflect.set(target, prop, value, receiver);
},
deleteProperty(target, prop) {
log(`delete ${String(prop)}`);
return Reflect.deleteProperty(target, prop);
}
});
}
const settings = withLogging({ theme: 'dark' });
settings.theme; // logs "get theme"
settings.fontSize = 14; // logs "set fontSize = 14"
delete settings.theme; // logs "delete theme"String(prop) is required because prop can be a symbol. A template literal throws a TypeError when it tries to convert a symbol implicitly.
Defaults: Never Return undefined
A defaults proxy returns a fallback value for any property the target does not have. This pattern works well for counters.
function withDefaults(target, defaultValue) {
return new Proxy(target, {
get(target, prop, receiver) {
return Reflect.has(target, prop)
? Reflect.get(target, prop, receiver)
: defaultValue;
}
});
}
const counts = withDefaults({}, 0);
for (const word of ['a', 'b', 'a']) {
counts[word] += 1;
}
console.log(Object.entries(counts)); // [['a', 2], ['b', 1]]The check uses Reflect.has instead of an own-property check, so inherited members such as toString still resolve normally.
Hidden Properties: Treat Underscore Keys as Private
A hiding proxy has to cover every way of observing a property. If it misses one, the property leaks through that path.
const isHidden = (key) => typeof key === 'string' && key.startsWith('_');
function hideUnderscored(target) {
return new Proxy(target, {
get(target, prop, receiver) {
return isHidden(prop) ? undefined : Reflect.get(target, prop, receiver);
},
has(target, prop) {
return isHidden(prop) ? false : Reflect.has(target, prop);
},
ownKeys(target) {
return Reflect.ownKeys(target).filter((key) => !isHidden(key));
},
getOwnPropertyDescriptor(target, prop) {
return isHidden(prop)
? undefined
: Reflect.getOwnPropertyDescriptor(target, prop);
}
});
}
const account = hideUnderscored({ _token: 'abc', owner: 'Ada' });
console.log(account._token); // undefined
console.log('_token' in account); // false
console.log(Object.keys(account)); // ['owner']
console.log(JSON.stringify(account)); // '{"owner":"Ada"}'This only works while the hidden properties are configurable. If a property is non-configurable, invariants require ownKeys to list it and getOwnPropertyDescriptor to report it. Otherwise the engine throws.
Composing Wrappers
Each factory returns an ordinary object, so you can nest the factories. The outermost proxy sees an operation first.
const order = withLogging(
withValidation({}, { qty: (v) => Number.isInteger(v) && v > 0 })
);
order.qty = 3; // logs "set qty = 3", then validation passes
try {
order.qty = 0; // logs "set qty = 0", then validation throws
} catch (err) {
console.log(err.message);
}| Pattern | Traps used | Common mistake |
|---|---|---|
| Validation | `set` | Looking up rules with inherited keys |
| Logging | `get`, `set`, `deleteProperty` | Interpolating symbol keys without `String()` |
| Defaults | `get` | Answering `then` or `toJSON` probes |
| Hidden properties | `get`, `has`, `ownKeys`, `getOwnPropertyDescriptor` | Leaving one observation path untrapped |
Exercise
With the order matches the composed example, but you swap the nesting to withValidation(withLogging({}), rules). What is logged when you run order.qty = 0, and why?
Show answer
Nothing is logged. The validation proxy is now the outer one, so its set trap runs first and throws before it calls Reflect.set. The inner logging proxy never receives the operation.
Exercise
The defaults proxy above uses Reflect.has(target, prop). What would counts.toString return if you replaced that check with Object.hasOwn(target, prop), and why?
Show answer
It would return 0. toString is inherited from Object.prototype, not an own property, so the own-property check fails and the trap returns the default value instead of the function.