Sub topic 7
Controlling in, delete, and Key Enumeration
This chapter assumes you have read the earlier chapters on handler traps and the Reflect API. You should be comfortable writing a get or set trap that forwards to the target with the matching Reflect method. It also assumes you know what an enumerable property is.
Reads and writes are only part of what code does with an object. Code also checks whether a property exists, deletes properties, and lists an object's keys. Three traps cover these operations: has, deleteProperty, and ownKeys.
Which operations reach which trap
Each trap corresponds to one internal method. Several language features can share the same internal method.
| Trap | Internal method | Triggered by | Reflect default |
|---|---|---|---|
| `has` | `[[HasProperty]]` | `prop in obj`, `with` statements | `Reflect.has` |
| `deleteProperty` | `[[Delete]]` | `delete obj.prop` | `Reflect.deleteProperty` |
| `ownKeys` | `[[OwnPropertyKeys]]` | `Object.keys`, `Object.getOwnPropertyNames`, `Object.getOwnPropertySymbols`, `Reflect.ownKeys`, `for...in`, `JSON.stringify`, object spread | `Reflect.ownKeys` |
The has trap does not fire for obj.hasOwnProperty(prop) or Object.hasOwn(obj, prop). Those calls use [[GetOwnProperty]] instead, which goes to the getOwnPropertyDescriptor trap.
A record with hidden keys
The example below treats any key that starts with an underscore as private. The proxy reports those keys as absent, refuses to delete them, and leaves them out of key listings.
'use strict';
const isHidden = (key) => typeof key === 'string' && key.startsWith('_');
const record = new Proxy({ _secret: 1, visible: 2 }, {
has(target, prop) {
return isHidden(prop) ? false : Reflect.has(target, prop);
},
deleteProperty(target, prop) {
if (isHidden(prop)) return false;
return Reflect.deleteProperty(target, prop);
},
ownKeys(target) {
return Reflect.ownKeys(target).filter((key) => !isHidden(key));
}
});
console.log('_secret' in record); // false
console.log('visible' in record); // true
console.log(Object.keys(record)); // ['visible']
console.log(JSON.stringify(record)); // {"visible":2}
try {
delete record._secret;
} catch (err) {
console.log(err instanceof TypeError); // true
}
delete record.visible;
console.log(Object.keys(record)); // []Each trap follows the same pattern. It handles the special case, then forwards everything else to the matching Reflect method, so ordinary keys and symbol keys behave normally.
What the return values mean
hasreturns a boolean, and theinoperator gives that boolean back to the caller.deletePropertyreturns a boolean that reports success. If it returnsfalse, adeletein strict-mode code throws aTypeError. In sloppy-mode code the samedeletejust evaluates tofalse. Modules and class bodies are always strict.ownKeysmust return an array-like list of strings and symbols with no duplicates. A number in that list, or a repeated key, makes the engine throw.
Common errors
- Adding keys in
ownKeysand expecting them inObject.keys.Object.keysasks[[GetOwnProperty]]about each key and keeps only the enumerable ones. A key that you invent inownKeysbut that does not exist on the target is silently dropped. You also need agetOwnPropertyDescriptortrap that returns an enumerable, configurable descriptor for that key. - Filtering out non-configurable keys. The engine requires
ownKeysto report every non-configurable own property of the target. If the target is non-extensible, the list must match the target's keys exactly. A later chapter covers these invariants. - Forgetting symbol keys.
Reflect.ownKeysreturns symbols as well as strings. If your filter callskey.startsWithon every key, a symbol key will throw. Thetypeof key === 'string'check inisHiddenprevents that.
Exercise
Using the record proxy from this chapter, what do Object.hasOwn(record, '_secret') and record._secret return, and why?
Show answer
Both expose the hidden property. Object.hasOwn returns true because it uses [[GetOwnProperty]], which goes to the getOwnPropertyDescriptor trap. That trap is not defined, so the call falls through to the target. record._secret returns 1 because there is no get trap. The has and ownKeys traps only affect in and key enumeration.
Exercise
Write a deleteProperty trap that lets callers delete any property except id. Deleting id should fail with a TypeError in strict mode.
Show answer
deleteProperty(target, prop) { if (prop === 'id') return false; return Reflect.deleteProperty(target, prop); } Returning false makes a strict-mode delete proxy.id throw a TypeError. Every other key is forwarded to Reflect.deleteProperty.