Sub topic 7
Controlling in, delete, and Key Enumeration
Earlier chapters covered reads and writes with get and set, and forwarding through Reflect with the correct receiver. This chapter covers three other traps that control whether a property seems to exist:
hasanswers the question "is this key here?"deletePropertydecides whether a key can be removed.ownKeysdecides which keys show up when code lists an object's properties.
This chapter assumes you know property descriptors (enumerable, configurable), the prototype chain, strict mode, and the Reflect methods introduced earlier. The traps here are simple to write. The hard part is knowing which language operations reach each trap and which ones go around it. Most bugs come from that second question.
Which Operations Reach Which Trap
Each trap corresponds to one internal method. has maps to [[HasProperty]], deleteProperty maps to [[Delete]], and ownKeys maps to [[OwnPropertyKeys]]. Many built-in operations call more than one internal method, so a single line of your code can fire several traps.
| Operation | Traps it calls on the proxy |
|---|---|
| `'k' in p` | `has` |
| `with (p) { k }` (sloppy mode only) | `has`, then `get` |
| `Reflect.has(p, 'k')` | `has` |
| `'k' in child` where `p` is in `child`'s prototype chain | `has` (when `child` lacks `k`) |
| `delete p.k`, `Reflect.deleteProperty(p, 'k')` | `deleteProperty` |
| `Reflect.ownKeys(p)`, `Object.getOwnPropertyNames(p)`, `Object.getOwnPropertySymbols(p)` | `ownKeys` |
| `Object.keys(p)` | `ownKeys`, then `getOwnPropertyDescriptor` for each key |
| `Object.entries(p)`, `Object.values(p)`, `JSON.stringify(p)`, `{ ...p }`, `Object.assign({}, p)` | `ownKeys`, `getOwnPropertyDescriptor`, then `get` |
| `for (const k in p)` | `ownKeys`, `getOwnPropertyDescriptor`, `getPrototypeOf` |
| `Object.hasOwn(p, 'k')`, `p.hasOwnProperty('k')` | `getOwnPropertyDescriptor` (not `has`) |
Two rows in that table cause most of the surprises. Object.hasOwn does not call has. Object.keys does not trust ownKeys alone. Both come up again below.
The has Trap
The has trap receives (target, prop) and must return a value that the engine converts to a boolean. The default behavior is Reflect.has(target, prop), which walks the prototype chain the same way in does.
const range = new Proxy({}, {
has(target, prop) {
if (typeof prop !== 'string') {
return Reflect.has(target, prop);
}
const n = Number(prop);
return Number.isInteger(n) && n >= 1 && n <= 10;
}
});
console.log(5 in range); // true
console.log(11 in range); // false
console.log('x' in range); // false
console.log(Symbol.iterator in range); // falseNotice two details:
5 in rangepasses the string'5', not the number5. Property keys are always strings or symbols by the time they reach a trap.- The
typeofguard is necessary.Number(Symbol.iterator)throws aTypeError, and engines and libraries do probe objects with symbol keys. Any trap that converts or parsespropshould handle symbols first.
has only controls the answer to existence checks. It does not change what range[5] returns. That read goes through get, and since no get trap exists here, range[5] is undefined. A proxy that says a key exists but returns undefined for it is legal, but it confuses callers. Keep has and get consistent unless you have a reason not to.
The deleteProperty Trap
The deleteProperty trap receives (target, prop) and returns a boolean. true means the deletion succeeded. false means it was refused. Strict mode changes what callers see when the trap returns false:
Reflect.deletePropertyreturnsfalse.- The
deleteoperator in sloppy mode returnsfalse. - The
deleteoperator in strict mode (which includes modules and class bodies) throws aTypeError.
const config = new Proxy({ host: 'localhost', port: 8080 }, {
deleteProperty(target, prop) {
if (prop === 'host') {
return false;
}
return Reflect.deleteProperty(target, prop);
}
});
function strictDelete(obj, key) {
'use strict';
return delete obj[key];
}
console.log(Reflect.deleteProperty(config, 'host')); // false
console.log(strictDelete(config, 'port')); // true
console.log('port' in config); // false
try {
strictDelete(config, 'host');
} catch (err) {
console.log(err instanceof TypeError); // true
}Returning false lets the engine pick the behavior for each caller. Throwing your own error gives a clearer message ('host' is required), but it throws even for callers who used Reflect.deleteProperty and expected a boolean. Choose deliberately. Library code usually returns false. Application code that wants loud failures often throws.
The ownKeys Trap
The ownKeys trap receives (target) and must return an array-like object of keys. The engine validates the result before it uses it:
- Every element must be a string or a symbol. A number such as
1throws aTypeError. Use'1'. - No key may appear twice.
- The rules covered in the invariants chapter also apply. For example, you cannot drop a non-configurable key.
ownKeys returns all own keys: strings and symbols, enumerable and non-enumerable. Each caller filters the list for itself. Object.getOwnPropertySymbols keeps only symbols, and Object.keys keeps only enumerable strings. To decide what counts as enumerable, Object.keys asks getOwnPropertyDescriptor about each key. That second lookup causes the most common ownKeys bug:
const virtual = new Proxy({}, {
ownKeys() {
return ['a', 'b'];
}
});
console.log(Reflect.ownKeys(virtual)); // ['a', 'b']
console.log(Object.keys(virtual)); // []Object.keys received ['a', 'b'] and then looked up a descriptor for each key on the target. The target has neither key, so each lookup returned undefined and the key was dropped. To make virtual keys visible, report a descriptor for them too, and add a get trap so that Object.entries and spread can read the values:
const values = { a: 1, b: 2 };
const virtual = new Proxy({}, {
ownKeys() {
return Object.keys(values);
},
getOwnPropertyDescriptor(target, prop) {
if (Object.hasOwn(values, prop)) {
return { value: values[prop], writable: true, enumerable: true, configurable: true };
}
return Reflect.getOwnPropertyDescriptor(target, prop);
},
get(target, prop, receiver) {
if (Object.hasOwn(values, prop)) {
return values[prop];
}
return Reflect.get(target, prop, receiver);
}
});
console.log(Object.keys(virtual)); // ['a', 'b']
console.log(Object.entries(virtual)); // [['a', 1], ['b', 2]]
console.log({ ...virtual }); // { a: 1, b: 2 }The descriptor must say configurable: true. The target does not actually have these properties, and the engine refuses a trap that reports a non-configurable property the target lacks.
The order of the array you return becomes the order Reflect.ownKeys and Object.keys report. The engine does not re-sort your keys. That means a proxy can list integer-like keys in a non-numeric order, which no ordinary object can do.
Hiding Properties Consistently
A common goal is to hide "private" keys such as _token from outside code. Writing only has and ownKeys leaves gaps: Object.hasOwn still finds the key, and proxy._token still reads it. Look back at the table and cover every path:
const isHidden = (key) => typeof key === 'string' && key.startsWith('_');
function hidePrivate(obj) {
return new Proxy(obj, {
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);
},
get(target, prop, receiver) {
return isHidden(prop) ? undefined : Reflect.get(target, prop, receiver);
},
deleteProperty(target, prop) {
return isHidden(prop) ? false : Reflect.deleteProperty(target, prop);
}
});
}
const account = hidePrivate({ _token: 'abc123', owner: 'ada' });
console.log('_token' in account); // false
console.log(Object.keys(account)); // ['owner']
console.log(Object.hasOwn(account, '_token')); // false
console.log(account._token); // undefined
console.log(JSON.stringify(account)); // {"owner":"ada"}
console.log({ ...account }); // { owner: 'ada' }
console.log(Reflect.deleteProperty(account, '_token')); // falseReturning undefined from getOwnPropertyDescriptor for a property that really exists is allowed here only because _token is configurable and the target is extensible. If the target were frozen, the engine would throw on these lies. The invariants chapter explains the exact rules.
This wrapper still has known gaps:
- Writes still go through.
account._token = 'x'overwrites the hidden value, because there is nosetordefinePropertytrap. Add one if hidden keys must be read-only from outside. - The object's own methods see the proxy. If
objhad a methodgetToken() { return this._token; }, callingaccount.getToken()setsthisto the proxy, so the method getsundefined. Hiding by name hides the key from the object itself too. For real privacy, use#privatefields or closures. A proxy only filters what callers see. - Debugging tools may bypass traps. Node's
console.log(account)inspects the target directly to avoid side effects, so it can print_token. Do not count on a proxy to keep secrets out of logs or debuggers.
Choosing Between the Traps
| Goal | Traps to implement |
|---|---|
| Make `in` reflect a rule (ranges, sets, permissions) | `has`, usually with `get` |
| Protect keys from removal | `deleteProperty` |
| Change which keys appear in listings | `ownKeys` plus `getOwnPropertyDescriptor` |
| Expose keys that the target does not store | `ownKeys`, `getOwnPropertyDescriptor`, `get`, `has` |
| Hide keys from every observer | `has`, `ownKeys`, `getOwnPropertyDescriptor`, `get`, `deleteProperty`, and possibly `set` and `defineProperty` |
The rule of thumb: a proxy should give the same answer to every way of asking a question. If in says no but Object.hasOwn says yes, callers end up depending on which check they happened to use.
Exercise
A proxy's ownKeys trap returns ['x'], its target is an empty object, and there are no other traps. What do Reflect.ownKeys(p), Object.keys(p), and Object.hasOwn(p, 'x') return, and why?
Show answer
Reflect.ownKeys(p) returns ['x'] because it uses the ownKeys result directly. Object.keys(p) returns [] because it looks up a descriptor for 'x' on the target, gets undefined, and drops the key. Object.hasOwn(p, 'x') returns false because it calls getOwnPropertyDescriptor, not ownKeys or has.
Exercise
Inside an ES module, a proxy's deleteProperty trap returns false for the key 'id'. What happens with delete p.id, and what happens with Reflect.deleteProperty(p, 'id')?
Show answer
Module code always runs in strict mode, so delete p.id throws a TypeError. Reflect.deleteProperty(p, 'id') never throws for a refused deletion and returns false.
Exercise
Write a has trap that reports true only for keys in an allowed Set named allowed, and that defers to the target for symbol keys.
Show answer
has(target, prop) { return typeof prop === 'symbol' ? Reflect.has(target, prop) : allowed.has(prop); }
Exercise
The hidePrivate wrapper above hides token, but account.token = 'new' still changes the stored value. Which trap would you add to block this, and what should it return for hidden keys?
Show answer
Add a set trap, set(target, prop, value, receiver) { return isHidden(prop) ? false : Reflect.set(target, prop, value, receiver); }. Returning false makes the assignment throw a TypeError in strict mode and fail silently in sloppy mode. Add a matching defineProperty trap to also block Object.defineProperty.