Sub topic 5
Reflect: The Default Behavior for Every Trap
This chapter assumes you know how to create a proxy from a target and a handler, that you have written simple get and set traps, and that you know each trap corresponds to an internal method such as [[Get]] or [[DefineOwnProperty]]. You should also be comfortable with property descriptors and with Function.prototype.apply.
In the earlier chapters, the get trap ended with a call like Reflect.get(target, prop, receiver). This chapter covers what that call does, why Reflect exists, and why it is the right way to finish almost every trap.
What Reflect Is
Reflect is a built-in namespace object, like Math or JSON. You cannot call it or use new with it. It holds 13 static methods, one for each proxy trap, and each method has the same name and parameter list as its trap.
Each Reflect method runs the matching internal method on the object you pass in. Reflect.get(obj, 'x') runs obj.[[Get]]('x', obj). Reflect.ownKeys(obj) runs obj.[[OwnPropertyKeys]](). Without a proxy involved, a Reflect call does exactly what the language does for the equivalent syntax.
Because the names and signatures match, a trap can pass its arguments straight through to Reflect and get the default behavior. You then add custom logic before or after that call.
The Full Mapping
| Trap | Reflect method | Closest older equivalent | Key difference |
|---|---|---|---|
| `get` | `Reflect.get(t, key, receiver)` | `t[key]` | Accepts an explicit receiver |
| `set` | `Reflect.set(t, key, value, receiver)` | `t[key] = value` | Returns a boolean, never throws on a failed write |
| `has` | `Reflect.has(t, key)` | `key in t` | Function form of the operator |
| `deleteProperty` | `Reflect.deleteProperty(t, key)` | `delete t[key]` | Returns a boolean even in strict mode |
| `ownKeys` | `Reflect.ownKeys(t)` | `Object.getOwnPropertyNames` plus `Object.getOwnPropertySymbols` | Returns string and symbol keys in one array |
| `defineProperty` | `Reflect.defineProperty(t, key, desc)` | `Object.defineProperty` | Returns a boolean instead of throwing |
| `getOwnPropertyDescriptor` | `Reflect.getOwnPropertyDescriptor(t, key)` | `Object.getOwnPropertyDescriptor` | Throws on non-object targets instead of coercing |
| `getPrototypeOf` | `Reflect.getPrototypeOf(t)` | `Object.getPrototypeOf` | Throws on non-object targets |
| `setPrototypeOf` | `Reflect.setPrototypeOf(t, proto)` | `Object.setPrototypeOf` | Returns a boolean instead of throwing |
| `isExtensible` | `Reflect.isExtensible(t)` | `Object.isExtensible` | Throws on non-object targets |
| `preventExtensions` | `Reflect.preventExtensions(t)` | `Object.preventExtensions` | Returns a boolean instead of the object |
| `apply` | `Reflect.apply(fn, thisArg, args)` | `fn.apply(thisArg, args)` | Cannot be broken by an overridden `apply` |
| `construct` | `Reflect.construct(C, args, newTarget)` | `new C(...args)` | Accepts a separate `newTarget` |
Booleans Instead of Exceptions
Several traps must return a boolean. set, deleteProperty, defineProperty, setPrototypeOf, and preventExtensions all report success or failure with true or false. The engine then decides what to do with a false: in strict-mode code it throws a TypeError, and in sloppy-mode code the operation fails silently.
The older Object methods do not fit that contract. Object.defineProperty throws when it fails, and on success it returns the object rather than true. Reflect.defineProperty returns the boolean the trap needs.
const obj = Object.preventExtensions({});
console.log(Reflect.defineProperty(obj, 'x', { value: 1 })); // false
try {
Object.defineProperty(obj, 'x', { value: 1 });
} catch (err) {
console.log(err instanceof TypeError); // true
}The same pattern holds for writes and deletes. Here a frozen object rejects both, and Reflect reports the result without throwing:
'use strict';
const frozen = Object.freeze({ x: 1 });
console.log(Reflect.set(frozen, 'x', 2)); // false
console.log(Reflect.deleteProperty(frozen, 'x')); // false
console.log(frozen.x); // 1
try {
frozen.x = 2; // strict mode: assignment to a read-only property throws
} catch (err) {
console.log(err instanceof TypeError); // true
}When a set trap returns Reflect.set(...), a failed write produces the language's normal behavior: an error in strict code, silence in sloppy code. The trap never has to decide which one applies.
Stricter Argument Checks
Object methods often coerce primitives. Object.getPrototypeOf(1) returns Number.prototype, and Object.keys('ab') returns ['0', '1']. The Reflect methods require an object as the first argument and throw a TypeError otherwise.
console.log(Object.getPrototypeOf(1) === Number.prototype); // true
try {
Reflect.getPrototypeOf(1);
} catch (err) {
console.log(err instanceof TypeError); // true
}Inside a trap, the target is always an object, so this check never gets in your way. Outside traps, it catches the bugs that silent coercion would hide.
Methods Worth a Closer Look
Reflect.ownKeys
Reflect.ownKeys returns every own key: enumerable and non-enumerable, strings and symbols. Integer-like keys come first in ascending order, then other strings in creation order, then symbols in creation order. Object.keys returns only enumerable string keys, which is a filtered view of this list.
const tag = Symbol('tag');
const obj = { b: 1, 2: 'two', a: 2, [tag]: 'sym', 1: 'one' };
Object.defineProperty(obj, 'hidden', { value: 3, enumerable: false });
console.log(Reflect.ownKeys(obj)); // ['1', '2', 'b', 'a', 'hidden', Symbol(tag)]
console.log(Object.keys(obj)); // ['1', '2', 'b', 'a']An ownKeys trap must return this full list, symbols included, so Reflect.ownKeys is the correct starting point when you filter keys.
Reflect.apply
fn.apply(thisArg, args) looks up apply on fn. If someone has defined an own apply property on the function, or the object is not a real function, the call breaks. Reflect.apply calls the function's [[Call]] internal method directly.
function greet(greeting) {
return `${greeting}, ${this.name}`;
}
greet.apply = () => 'hijacked';
console.log(greet.apply({ name: 'Ada' }, ['Hi'])); // 'hijacked'
console.log(Reflect.apply(greet, { name: 'Ada' }, ['Hi'])); // 'Hi, Ada'
console.log(Reflect.apply(Math.max, undefined, [1, 3, 2])); // 3The arguments must be an array-like object. Unlike Function.prototype.apply, Reflect.apply throws if you pass null or undefined for the argument list.
Reflect.construct
Reflect.construct(C, args) behaves like new C(...args). The optional third argument, newTarget, sets the value of new.target inside the constructor, and the new object's prototype comes from newTarget.prototype.
class Base {
constructor() {
this.createdBy = new.target.name;
}
}
class Other {}
const a = Reflect.construct(Base, []);
const b = Reflect.construct(Base, [], Other);
console.log(a.createdBy, a instanceof Base); // 'Base' true
console.log(b.createdBy, b instanceof Other); // 'Other' true
console.log(b instanceof Base); // falseA construct trap receives newTarget as its third parameter. Passing it on to Reflect.construct keeps subclassing working when someone extends a proxied class, because new.target stays the subclass.
Reflect.get and Reflect.set with a receiver
The receiver parameter sets the this value for any getter or setter found during the lookup. target[prop] always uses target as this, while Reflect.get(target, prop, receiver) uses whatever object you pass. The next chapter explains why forwarding the trap's receiver matters when proxies sit on a prototype chain. For now, the rule is that a trap should pass receiver through unchanged.
const obj = {
first: 'Ada',
get label() { return `user ${this.first}`; }
};
console.log(Reflect.get(obj, 'label')); // 'user Ada'
console.log(Reflect.get(obj, 'label', { first: 'Grace' })); // 'user Grace'Forwarding Every Trap Generically
Every Reflect method matches its trap by name and signature, so you can write one handler that intercepts every operation. The handler below is itself a proxy. When the engine looks up a trap such as handler.get or handler.ownKeys, the handler proxy's own get trap returns a function that logs the trap name and forwards to Reflect[trapName].
const tracingHandler = new Proxy({}, {
get(_handler, trapName) {
return (...args) => {
console.log(`trap: ${trapName}`);
return Reflect[trapName](...args);
};
}
});
const target = { a: 1, b: 2 };
const proxy = new Proxy(target, tracingHandler);
proxy.a; // trap: get
proxy.c = 3; // trap: set, trap: getOwnPropertyDescriptor, trap: defineProperty
'a' in proxy; // trap: has
delete proxy.c; // trap: deleteProperty
Object.keys(proxy); // trap: ownKeys, then getOwnPropertyDescriptor once per keyThis shows which internal methods each piece of syntax triggers. The set line logs three traps. Reflect.set receives the proxy as its receiver, and the default [[Set]] algorithm then defines the property on the receiver. Defining a property on the proxy goes through its getOwnPropertyDescriptor and defineProperty traps. Object.keys calls [[OwnPropertyKeys]] and then checks each key's descriptor to filter out non-enumerable properties.
When Not to Use Reflect
Reflect gives you the default behavior. When a trap deliberately replaces that behavior, for example a get trap that returns a computed default for missing keys, it does not need to call Reflect on that path. Even then, most traps use Reflect for every case they do not handle specially, so unrelated operations keep their normal semantics.
You also don't need Reflect in everyday code outside proxies. obj.x is clearer than Reflect.get(obj, 'x'). Reflect earns its place when you need its boolean results, its explicit receiver or newTarget, or its complete key list.
Summary
Reflectis a namespace of 13 functions, one per trap, with matching names and parameters.- Each function runs the corresponding internal method, so calling it from a trap produces the default behavior.
- Methods for boolean-returning traps report failure with
false, which is the value those traps must return. Reflectmethods throw on non-object targets instead of coercing them.Reflect.ownKeysreturns all own keys, including symbols and non-enumerables.Reflect.applyandReflect.constructcall[[Call]]and[[Construct]]directly, andconstructkeepsnewTarget.
Exercise
This trap is used in an ES module. Why does proxy.count = 1 throw a TypeError, and what one-line change fixes it?
const proxy = new Proxy({}, {
set(target, prop, value) {
console.log(writing ${String(prop)});
target[prop] = value;
}
});
Show answer
ES modules always run in strict mode. The trap returns undefined, which the engine treats as false, and in strict mode a set trap that reports failure causes a TypeError. Replace the assignment with return Reflect.set(target, prop, value, receiver); and add receiver as the fourth parameter. The trap then returns true when the write succeeds and false when it really fails, and it keeps setter this binding correct.
Exercise
You want an ownKeys trap that hides keys starting with "". A colleague writes `return Object.keys(target).filter(k => !k.startsWith(''));`. What does this break compared with starting from Reflect.ownKeys?
Show answer
Object.keys returns only enumerable string keys, so the trap silently drops every symbol key and every non-enumerable key. Object.getOwnPropertySymbols(proxy) would return nothing, and Object.getOwnPropertyNames would miss non-enumerable properties. If the target has a non-configurable property that is missing from the list, such as a non-enumerable one, the engine throws a TypeError. Start from Reflect.ownKeys(target) and filter only string keys, for example k => typeof k !== 'string' || !k.startsWith('_').
Exercise
What do these lines log, and why does the second result differ from the first? console.log(Reflect.defineProperty(Object.freeze({}), 'x', { value: 1 })); console.log(Reflect.construct(Array, [3]).length); console.log(Reflect.ownKeys([10, 20]));
Show answer
false, then 3, then ['0', '1', 'length']. The frozen object is not extensible, so the definition fails and Reflect.defineProperty returns false instead of throwing. Reflect.construct(Array, [3]) behaves like new Array(3), which creates an array of length 3. Reflect.ownKeys on an array returns the index keys and the non-enumerable length property, which Object.keys would leave out.