A Proxy is a stand-in for an object. Code uses the proxy exactly as if it were the real object. Behind the scenes, you can step in whenever a property is read, written, deleted or listed. That makes it possible to log every change, return default values, reject bad data or hide private fields, all without changing the original object. Reflect is its partner: a set of functions that perform the normal behaviour, so your proxy can add a little extra and then carry on as usual.
In this lesson you will learn
- Creating a Proxy with a target and a handler
- The
get,set,hasandownKeystraps - Default values, validation and logging with proxies
- What the
Reflectmethods do and why traps use them - When a Proxy is worth using, and when it is not
You should know objects, object methods and getters and setters.
Traps: Stepping In on Object Operations
// A Proxy wraps an object and lets "traps" step in on operations
const student = { name: "Rafi", marks: 78 };
const watched = new Proxy(student, {
get(target, prop, receiver) {
console.log(`reading "${String(prop)}"`);
return Reflect.get(target, prop, receiver); // do the normal thing
},
set(target, prop, value, receiver) {
console.log(`setting "${String(prop)}" to ${value}`);
return Reflect.set(target, prop, value, receiver);
}
});
console.log(watched.name);
watched.marks = 85;
console.log("original object changed too:", student.marks);
// Default values for missing keys
const prices = new Proxy({ rice: 82, dal: 135 }, {
get: (target, prop) => (prop in target ? target[prop] : "not in stock")
});
console.log(prices.rice, "|", prices.mango);
// Validation: reject bad values before they are stored
const account = new Proxy({ balance: 0 }, {
set(target, prop, value) {
if (prop === "balance" && (typeof value !== "number" || value < 0)) {
throw new TypeError(`balance must be a number of 0 or more, got ${value}`);
}
target[prop] = value;
return true; // tell JavaScript the assignment worked
}
});
account.balance = 500;
console.log("balance:", account.balance);
try { account.balance = -50; } catch (e) { console.log(e.message); }
Output
reading "name"
Rafi
setting "marks" to 85
original object changed too: 85
82 | not in stock
balance: 500
balance must be a number of 0 or more, got -50
new Proxy(target, handler)creates the proxy. The target is the real object; the handler is an object whose methods are called traps.- The
gettrap runs on every property read, andseton every write. Here they log the operation and then callReflect.getorReflect.setto do the normal work. - Changes made through the proxy reach the target, because the proxy passes them on. The proxy stores nothing itself.
- The
pricesproxy returns"not in stock"instead ofundefinedfor missing keys. - The
accountproxy checks values before saving them. Asettrap must returntruewhen it succeeds; returningfalsemakes the assignment fail with aTypeErrorin strict mode.
Reflect and More Traps
// Reflect has one method for each basic object operation
const book = { title: "Padma Nadir Majhi" };
console.log(Reflect.has(book, "title")); // same as "title" in book
console.log(Reflect.ownKeys(book)); // keys, including symbols
console.log(Reflect.defineProperty(book, "year", { value: 1936 })); // returns true/false
console.log(Reflect.deleteProperty(Object.freeze({ a: 1 }), "a")); // false instead of an error
// Hide "private" fields that start with an underscore
function hidePrivate(obj) {
return new Proxy(obj, {
has: (t, p) => !String(p).startsWith("_") && Reflect.has(t, p),
ownKeys: t => Reflect.ownKeys(t).filter(k => !String(k).startsWith("_")),
get: (t, p, r) => (String(p).startsWith("_") ? undefined : Reflect.get(t, p, r))
});
}
const user = hidePrivate({ name: "Mitu", email: "mitu@example.com", _password: "secret123" });
console.log(Object.keys(user));
console.log("_password" in user, user._password);
console.log(JSON.stringify(user));
// Negative array indexes, like Python
const list = arr => new Proxy(arr, {
get(t, p, r) {
const i = Number(p);
if (Number.isInteger(i) && i < 0) return t[t.length + i];
return Reflect.get(t, p, r);
}
});
const cities = list(["Dhaka", "Khulna", "Rajshahi", "Sylhet"]);
console.log(cities[-1], cities[-2], cities[0], cities.length);
Output
true
[ 'title' ]
true
false
[ 'name', 'email' ]
false undefined
{"name":"Mitu","email":"mitu@example.com"}
Sylhet Rajshahi Dhaka 4
- Each
Reflectmethod matches one trap and does the default job.Reflect.has(obj, key)works like theinoperator. - Reflect methods report failure by returning
falserather than throwing. Deleting a property from a frozen object returnsfalse. hidePrivateuses three traps.hascontrols theinoperator,ownKeyscontrolsObject.keysandJSON.stringify, andgethides the values.- The
listproxy adds Python-style negative indexes, socities[-1]is the last item. Note that property keys arrive as strings, so the trap converts them withNumber.
| Trap | Runs on | Matching Reflect method |
|---|---|---|
get | obj.x, obj[key] | Reflect.get |
set | obj.x = 1 | Reflect.set |
has | "x" in obj | Reflect.has |
deleteProperty | delete obj.x | Reflect.deleteProperty |
ownKeys | Object.keys, for...in | Reflect.ownKeys |
apply | Calling a function proxy | Reflect.apply |
When to Use a Proxy
Proxies power several popular tools. Vue uses them to notice when data changes and update the page automatically. Testing libraries use them to record how objects are used. In everyday code, a simple function or a class with getters and setters is often clearer. Proxies add a small cost to every operation, so avoid them in code that runs millions of times.
Common Mistakes
- Changing the original object directly and expecting the traps to run. Only operations on the proxy are trapped.
- Forgetting
return truein asettrap, which makes assignments fail in strict mode. - Writing
target[prop]instead ofReflect.get(target, prop, receiver)when the object has getters. Reflect passes the correctthis. - Treating a proxy as a security tool. Code that holds the original object can still read everything.
Practice Exercises
Exercise 1. Make a proxy that turns every string value into uppercase when it is read.
Show answer
const shout = obj => new Proxy(obj, {
get(t, p, r) {
const v = Reflect.get(t, p, r);
return typeof v === "string" ? v.toUpperCase() : v;
}
});
console.log(shout({ city: "Rajshahi", pop: 1 }).city); // "RAJSHAHI"
Exercise 2. Make a read-only proxy: any attempt to set or delete a property should throw an error.
Show answer
const readOnly = obj => new Proxy(obj, {
set() { throw new Error("This object is read-only"); },
deleteProperty() { throw new Error("This object is read-only"); }
});
Frequently Asked Questions
What is the difference between a Proxy and Object.freeze?
Object.freeze only stops changes. A Proxy can run any code you like on each operation: logging, validating, converting values or computing missing ones.
Can I turn a proxy off later?
Yes. Proxy.revocable(target, handler) returns both a proxy and a revoke function. After you call revoke(), any use of the proxy throws a TypeError.
Summary
- A Proxy wraps a target object, and handler traps step in on operations such as get, set and has.
- Reflect methods perform the default behaviour, so traps can add logic and then carry on normally.
- Proxies are good for defaults, validation, logging and hiding fields.
- Use simpler tools when they are enough; proxies add a small cost to every operation.
Next: JavaScript Symbols.
