Reflect API: object operations as functions (ES2015)
What you’ll learn
Section titled “What you’ll learn”- What the 13
Reflectmethods are and which operator orObjectmethod each one replaces. - How
Reflectreports failure (booleans andTypeErrors) differently fromObject. - What the
receiverargument ofReflect.getandReflect.setdoes, and why Proxy traps need it. - When
Reflectis the clearer choice and when a plain operator is better.
Summary
Section titled “Summary”TL;DR: Reflect is a plain namespace object (like Math) whose static methods perform the language’s basic object operations: reading, writing, deleting and defining properties, listing keys, reading and setting prototypes, calling functions and constructing objects. There is one method per Proxy trap, with the same name and arguments, so a trap can forward to the default behavior in one line.
Reflect was introduced in ECMAScript 2015 together with Proxy and is supported everywhere except Internet Explorer (see Compatibility). It is not a constructor and cannot be called.
The problem it solves
Section titled “The problem it solves”Before ES2015, the same low-level operations were scattered across operators (in, delete, new), Object methods with inconsistent failure modes, and Function.prototype.apply. Reflect gathers them in one place with consistent rules.
Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). ES modules are in strict mode. All outputs shown were produced with Node.js 22.23.
const order = Object.freeze({ id: 'A-100', status: 'paid' });
// Before: Object.defineProperty reports failure by throwing.try { Object.defineProperty(order, 'status', { value: 'refunded' });} catch (error) { console.log(`Object.defineProperty threw ${error.name}`);}
// After: Reflect.defineProperty returns a boolean you can branch on.if (!Reflect.defineProperty(order, 'status', { value: 'refunded' })) { console.log('Reflect.defineProperty returned false');}
// Operators become ordinary functions you can pass around.const fields = ['id', 'total'];console.log(fields.map((key) => Reflect.has(order, key)));
// Every own key, including symbols and non-enumerable ones.const audit = Symbol('audit');const draft = { id: 'A-101', [audit]: [] };Object.defineProperty(draft, 'internal', { value: true, enumerable: false });console.log(Object.keys(draft), Reflect.ownKeys(draft));
// Calling a function with an explicit this and argument list.function describe(prefix) { return `${prefix} ${this.id}`;}console.log(Function.prototype.apply.call(describe, order, ['Order']));console.log(Reflect.apply(describe, order, ['Order']));Output:
Object.defineProperty threw TypeErrorReflect.defineProperty returned false[ true, false ][ 'id' ] [ 'id', 'internal', Symbol(audit) ]Order A-100Order A-100Function.prototype.apply.call(...) is the safe way to call apply when a function might have its own apply property; Reflect.apply says the same thing directly.
How it works
Section titled “How it works”Reflect method |
Returns | Closest older form | Difference |
|---|---|---|---|
apply(fn, thisArg, args) |
call result | fn.apply(thisArg, args) |
args is required and must be array-like |
construct(C, args, newTarget?) |
new object | new C(...args) |
optional newTarget sets new.target and the prototype |
defineProperty(obj, key, desc) |
boolean | Object.defineProperty |
returns false instead of throwing |
deleteProperty(obj, key) |
boolean | delete obj[key] |
never throws for non-configurable properties |
get(obj, key, receiver?) |
value | obj[key] |
receiver is this for getters |
set(obj, key, value, receiver?) |
boolean | obj[key] = value |
returns false instead of throwing in strict mode |
has(obj, key) |
boolean | key in obj |
|
ownKeys(obj) |
array | Object.getOwnPropertyNames + Object.getOwnPropertySymbols |
strings and symbols in one array |
getOwnPropertyDescriptor(obj, key) |
descriptor or undefined |
Object.getOwnPropertyDescriptor |
throws for primitives instead of coercing |
getPrototypeOf(obj) |
object or null |
Object.getPrototypeOf |
throws for primitives instead of coercing |
setPrototypeOf(obj, proto) |
boolean | Object.setPrototypeOf |
returns false instead of throwing |
isExtensible(obj) |
boolean | Object.isExtensible |
throws for primitives instead of returning false |
preventExtensions(obj) |
boolean | Object.preventExtensions |
returns a boolean, not the object |
Two rules follow from the specification. First, every method throws a TypeError if the target is not an object; the Object versions often coerce primitives instead. Second, the methods that change an object return true or false for success rather than throwing, so the caller decides how to react.
// Reflect throws for primitives where Object coerces them.console.log(Object.getPrototypeOf('text') === String.prototype);try { Reflect.getPrototypeOf('text');} catch (error) { console.log(`${error.name}: ${error.message}`);}
// Reflect.set returns false instead of throwing, even in strict-mode modules.const locked = Object.freeze({ total: 10 });console.log(Reflect.set(locked, 'total', 20), locked.total);
// The receiver argument decides what `this` is inside getters and setters.const order = { id: 'A-100', get label() { return `Order ${this.id}`; },};console.log(Reflect.get(order, 'label'), '|', Reflect.get(order, 'label', { id: 'A-200' }));
// Reflect.construct: `new` as a function, with an optional newTarget.class Order { constructor(id) { this.id = id; this.kind = new.target.name; }}class RushOrder extends Order {}const built = Reflect.construct(Order, ['A-102'], RushOrder);console.log(built, built instanceof RushOrder);
// ownKeys order: integer-like keys ascending, then strings and symbols in insertion order.console.log(Reflect.ownKeys({ b: 1, 2: 1, [Symbol('s')]: 1, a: 1, 1: 1 }));Output:
trueTypeError: Reflect.getPrototypeOf called on non-objectfalse 10Order A-100 | Order A-200RushOrder { id: 'A-102', kind: 'RushOrder' } true[ '1', '2', 'b', 'a', Symbol(s) ]Reflect.construct ran Order’s constructor but created the object from RushOrder.prototype and set new.target to RushOrder. That is how a Proxy construct trap or a factory can build subclass instances without new.
Reflection has limits: Reflect.ownKeys never lists private fields, and Reflect.get cannot read them.
Realistic example
Section titled “Realistic example”OrdersPortal wraps orders in a debugging proxy that records every read and write. Each trap does its extra work and then forwards to the matching Reflect method with the same arguments, including receiver. The sample also shows the bug that happens without it: a trap that does obj[key] runs getters with the raw target as this, so the property reads inside the getter skip the proxy and are never logged.
// audited.mjs - OrdersPortal: record every read and write on an order for debugging.export function audited(target, log) { return new Proxy(target, { get(obj, key, receiver) { log.push(`get ${String(key)}`); return Reflect.get(obj, key, receiver); // receiver keeps getters running through the proxy }, set(obj, key, value, receiver) { if (key === 'status' && !['placed', 'paid', 'shipped'].includes(value)) { log.push(`reject status=${value}`); return false; // a strict-mode assignment then throws a TypeError } const ok = Reflect.set(obj, key, value, receiver); // false for frozen or read-only targets log.push(`set ${String(key)}=${value} ${ok ? 'ok' : 'failed'}`); return ok; }, deleteProperty(obj, key) { const ok = Reflect.deleteProperty(obj, key); log.push(`delete ${String(key)} ${ok ? 'ok' : 'failed'}`); return ok; }, });}
class Order { constructor(id, totalCents) { this.id = id; this.totalCents = totalCents; this.status = 'placed'; } get summary() { return `${this.id} ${this.status} ${this.totalCents}`; }}
// A naive trap that ignores the receiver: the getter's `this` is the raw target.const naiveLog = [];const naive = new Proxy(new Order('A-1', 4900), { get(obj, key) { naiveLog.push(`get ${String(key)}`); return obj[key]; },});naive.summary;console.log('naive: ', naiveLog.join(', '));
const log = [];const order = audited(new Order('A-2', 5200), log);order.summary;order.status = 'paid';delete order.totalCents;console.log('audited:', log.join(', '));
log.length = 0;try { order.status = 'teleported';} catch (error) { console.log(`${error.name}: ${error.message}`);}const frozen = audited(Object.freeze(new Order('A-3', 100)), log);console.log('Reflect.set via proxy:', Reflect.set(frozen, 'status', 'paid'));console.log(log);Output:
naive: get summaryaudited: get summary, get id, get status, get totalCents, set status=paid ok, delete totalCents okTypeError: 'set' on proxy: trap returned falsish for property 'status'Reflect.set via proxy: false[ 'reject status=teleported', 'set status=paid failed' ]The set trap must return a boolean. Returning the result of Reflect.set means a frozen target is reported correctly: a strict-mode assignment throws, while a caller using Reflect.set itself gets false.
Common mistakes
Section titled “Common mistakes”- Dropping
receiverwhen forwarding.Reflect.get(obj, key)inside agettrap runs getters with the target asthis, as the naive sample shows. Always pass all trap arguments through. - Ignoring the boolean.
Reflect.set,defineProperty,deleteProperty,setPrototypeOfandpreventExtensionsdo not throw on failure. Code that ignores the result silently loses writes. Check it, or use the operator in strict mode so failure throws. - Using
Reflect.hasorReflect.ownKeysas an own-property check.Reflect.hasfollows the prototype chain likein. For own properties useObject.hasOwn(). - Expecting
Reflect.apply(fn, thisArg)to work without arguments. The argument list is required: it throwsTypeError: CreateListFromArrayLike called on non-object. Pass[]. - Looking for
Reflect.metadataorReflect.defineMetadata. They are not part of ECMAScript. They come from thereflect-metadatanpm package, used with TypeScript’s legacyexperimentalDecoratorsandemitDecoratorMetadata. - Double-logging with extra traps. When
receiveris the proxy,Reflect.setreads and defines the property through the proxy, sogetOwnPropertyDescriptoranddefinePropertytraps also run for that write. That is correct behavior; just log in one place.
When to use it and when not to
Section titled “When to use it and when not to”Use Reflect:
- In every Proxy trap, to perform the default behavior with exactly the trap’s arguments.
- When you need a success flag rather than an exception (generic utilities, defensive copying, sandboxed or frozen inputs).
- When an operator must be a value: passing
Reflect.hasorReflect.deletePropertyas a callback. - For all own keys at once (
Reflect.ownKeys) in cloning, diffing and serialization helpers. - To construct with a different
new.targetin factories and proxies.
Prefer the plain form (obj.key, key in obj, new C(), Object.keys) in ordinary application code: it is shorter, faster to read, and in strict mode it already throws on failure, which is usually what you want.
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data (@mdn/browser-compat-data 8.1.9), Reflect and all 13 methods are supported in Chrome 49, Edge 12, Firefox 42, Safari 10 (iOS 10), Node.js 6.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it. Reflect can be polyfilled (for example by core-js), but Proxy cannot, so the main use case still needs a native engine.
Interview questions
Section titled “Interview questions”1. Why does Reflect exist when Object already has defineProperty and getPrototypeOf?
It gives each internal object operation exactly one function, with arguments that match the Proxy trap of the same name, consistent TypeErrors for non-object targets, and boolean results instead of exceptions. It also turns operators such as in, delete and new into functions.
2. What is the receiver in Reflect.get(target, key, receiver)?
It is the this value used if the property is an accessor. In a Proxy trap it is normally the proxy itself, so forwarding it keeps the getter’s own property reads going through the proxy. Without it, the getter sees the raw target.
3. What does Reflect.construct(Order, args, RushOrder) do?
It runs Order’s constructor with new.target set to RushOrder, so the new object inherits from RushOrder.prototype. It is new as a function, with control over the prototype.
4. What is the difference between Object.keys(obj) and Reflect.ownKeys(obj)?
Object.keys returns only own, enumerable, string keys. Reflect.ownKeys returns every own key: enumerable or not, strings and symbols. Neither includes inherited keys or private fields.
5. Senior scenario: you are building a change-tracking layer for OrdersPortal forms using proxies. What role does Reflect play, and what can go wrong?
Each trap records the change and then forwards with Reflect and the full argument list, returning its boolean so frozen or read-only targets fail correctly. Forwarding receiver makes getters and setters on the model, including inherited ones, run against the proxy so their internal reads and writes are tracked. Risks: class instances with #private fields break behind a proxy, so the layer should wrap plain data objects; nested objects need wrapping on read (cache the wrapper in a WeakMap so identity is stable); and defineProperty traps also fire on forwarded sets, so log in one place.
Key takeaways
Section titled “Key takeaways”Reflect(ES2015) has 13 static methods, one per internal object operation and Proxy trap.- Mutating methods return booleans instead of throwing; all methods throw for non-object targets.
- Pass
receiverthrough in Proxy traps so getters and setters see the proxy asthis. Reflect.ownKeyslists every own string and symbol key, but never private fields.- In ordinary code, operators and
Objectmethods are usually clearer.
Related pages
Section titled “Related pages”- Proxy: the traps that
Reflectmethods forward to. - Private fields: what reflection and proxies cannot see.
- Symbol: symbol keys returned by
Reflect.ownKeys. - Object.getOwnPropertyDescriptors: descriptors for every own key at once.
- Object.hasOwn: the own-property check
Reflect.hasis not. - Prototypes: the chain that
get,setandhaswalk.
Official references
Section titled “Official references”- ECMAScript Language Specification: The Reflect Object (current draft; first published in ECMAScript 2015, 6th edition)
- ECMAScript 2015 Language Specification (ECMA-262, 6th edition): The Reflect Object
- MDN: Reflect
- MDN: Meta programming guide