Reflect API in JavaScript
Introduction
The Reflect object provides a standard set of methods for operations you used to do only through syntax or older APIs: property definition, deletion, prototype access, and function application. Proxy traps often forward to Reflect to keep default behavior—this chapter covers Reflect on its own first.
Prerequisites
Reflect.get / Reflect.set
javascript
const target = { x: 1, y: 2 };
console.log(Reflect.get(target, "x"));
Reflect.set(target, "y", 20);
console.log(target.y);Works like target.x with explicit receiver for getters:
javascript
const holder = {
_val: 0,
get value() {
return this._val;
},
};
const receiver = { _val: 99 };
console.log(Reflect.get(holder, "value", receiver));Reflect.has
javascript
// Like "key" in obj
const obj = { a: 1 };
console.log(Reflect.has(obj, "a"));
console.log(Reflect.has(obj, "toString"));Reflect.deleteProperty
javascript
const data = { temp: true, keep: 1 };
Reflect.deleteProperty(data, "temp");
console.log(data);Reflect.defineProperty
javascript
const locked = {};
Reflect.defineProperty(locked, "id", {
value: 1,
writable: false,
});
console.log(locked.id);Returns boolean success (unlike defineProperty throwing in strict assignment failures in some cases).
Reflect.apply and Reflect.construct
javascript
// Call function with explicit this and args array
function greet(greeting, name) {
return `${greeting}, ${name}`;
}
console.log(Reflect.apply(greet, null, ["Hello", "Ada"]));
// Like new Constructor(...args)
function Point(x, y) {
this.x = x;
this.y = y;
}
const p = Reflect.construct(Point, [3, 4]);
console.log(p.x, p.y);Reflect.getPrototypeOf / setPrototypeOf
javascript
const base = { kind: "base" };
const child = {};
Reflect.setPrototypeOf(child, base);
console.log(Reflect.getPrototypeOf(child) === base);Mini Example: Unified Property Copy
javascript
function copyOwnProperties(from, to) {
for (const key of Reflect.ownKeys(from)) {
const desc = Object.getOwnPropertyDescriptor(from, key);
if (desc) Reflect.defineProperty(to, key, desc);
}
return to;
}
const src = { a: 1 };
const sym = Symbol("meta");
src[sym] = "ok";
const dest = {};
copyOwnProperties(src, dest);
console.log(dest.a, dest[sym]);FAQ
Why Reflect if syntax exists?
Consistent return values for meta operations and pairing with Proxy traps.
Reflect vs Object.*?
Overlap exists—Reflect methods often match Proxy trap names one-to-one.
Must beginners use it daily?
Rare in app code until debugging Proxies or reading framework source.