What are Proxy traps in JavaScript?
Traps are the handler methods on a Proxy that intercept operations on the target object.
get / set — intercept reading and writing properties.
has — intercept the in operator.
deleteProperty — intercept delete.
apply / construct — intercept function calls and new.
Tip: use Reflect inside traps to perform the default behaviour after your custom logic.
const handler = {
get(target, prop, receiver) {
console.log(`Accessing: ${String(prop)}`);
return prop in target ? target[prop] : `No property '${String(prop)}'`;
},
set(target, prop, value) {
if (prop === 'age' && (typeof value !== 'number' || value < 0)) {
throw new TypeError('Age must be a positive number');
}
target[prop] = value;
return true;
},
has(target, prop) {
console.log(`Checking: ${String(prop)}`);
return prop in target;
},
deleteProperty(target, prop) {
if (prop === 'id') throw new Error('Cannot delete id');
delete target[prop];
return true;
}
};
const user = new Proxy({ id: 1, name: 'John' }, handler);
user.name; // Logs: 'Accessing: name' -> 'John'
user.missing; // -> "No property 'missing'"
user.age = 30; // OK
// user.age = -5; // TypeError!
'name' in user; // Logs: 'Checking: name' -> true
// delete user.id; // Error: Cannot delete idget intercepts property reads (returns default for missing). set validates before assignment (rejects negative age). has intercepts the in operator. deleteProperty prevents deleting protected properties. Each trap receives the target object and returns a value or boolean.
Know 4-5 traps: get (read), set (write), has (in), deleteProperty (delete), apply (call). The validation pattern (reject invalid values in set) is the most practical.
Mention Vue 3 using Proxy for reactivity.