0 day streak
javascript / intermediate
Snippet

Intercepting Operations with Proxy

The Proxy object allows you to create a wrapper for another object to intercept and redefine fundamental operations like property access, assignment, and enumeration.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
const user = { name: 'Alice' };
const proxy = new Proxy(user, {
get: (target, prop) => prop in target ? target[prop] : 'Property not found',
set: (target, prop, value) => {
if (prop === 'age' && value < 0) throw new Error('Invalid age');
target[prop] = value;
return true;
}
});
Breakdown
1
get: (target, prop) => prop in target ? target[prop] : 'Property not found',
Defines a 'trap' for reading properties, providing a fallback value if the key doesn't exist.
2
set: (target, prop, value) => { ... }
Defines a 'trap' for writing properties, enabling validation logic before the update occurs.