The JavaScript Reflect object
The Reflect object is a built-in namespace of methods that perform the default low-level operations on objects: Reflect.get(), Reflect.set(), Reflect.has(), Reflect.ownKeys(). Its main purpose is to be called inside Proxy traps to run the normal behavior after your custom logic.
Overview
Reflect is a static namespace (like Math) whose methods mirror the fundamental operations you can do to an object: Reflect.get(obj, key) reads a property, Reflect.set(obj, key, value) writes one, Reflect.has(obj, key) is the in operator as a function, Reflect.deleteProperty() deletes, and Reflect.ownKeys() lists keys. Each does exactly what the corresponding language operation does, but as a callable function.
Its primary reason to exist is to pair with Proxy. The Reflect methods map one-to-one to the Proxy traps, so inside a trap you call the matching Reflect method to perform the default behavior cleanly: get(target, prop, receiver) { /* custom */ return Reflect.get(target, prop, receiver); }. This is more correct than target[prop] because it forwards the receiver properly and returns sensible values.
It also tidies up a few operations that were historically awkward or threw inconsistently. Reflect.set() returns a boolean for success instead of throwing, and Reflect.ownKeys() returns all own keys including symbols. Outside of Proxy work you rarely need Reflect directly (for everyday code, the normal syntax and Object methods are clearer), but when writing proxies, it's the right companion.
Syntax
Reflect.get(obj, "name"); // obj.name
Reflect.set(obj, "name", "Ada"); // obj.name = "Ada" (returns boolean)
Reflect.has(obj, "name"); // "name" in obj
Reflect.ownKeys(obj); // all own keys, including symbols
// inside a Proxy trap
get(target, prop, receiver) {
return Reflect.get(target, prop, receiver);
}
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const user = { name: 'Ada' };
document.getElementById('out').textContent =
'get: ' + Reflect.get(user, 'name') + '\n' +
'has: ' + Reflect.has(user, 'name') + '\n' +
'keys: ' + Reflect.ownKeys(user).join(', '); // Ada / true / name
</script>
Best practices
- Use
Reflectmethods inside Proxy traps to perform the default operation correctly. - Prefer
Reflect.get/setovertarget[prop]in traps to forward thereceiverproperly. - Use
Reflect.ownKeys()when you need all own keys including symbols. - In ordinary code (no proxies), normal syntax and Object methods are clearer.