Back to results for “Design Patterns in JavaScript”
JavaScript › Design Patterns in JavaScript

How do you implement the Proxy pattern using JavaScript's built-in Proxy object?

Advanced

Answer

JavaScript's native Proxy wraps a target object with traps (get, set, has, etc.) that intercept and can customize fundamental operations on it, letting you add validation, logging, or virtual properties transparently.
const validated = new Proxy({}, {
  set(target, prop, value) {
    if (prop === 'age' && value < 0) throw new Error('Invalid age');
    target[prop] = value;
    return true;
  }
});
validated.age = -5; // throws
Real-world example Building a reactive state object (like Vue 3's reactivity system) that tracks property reads and writes.

Common follow-ups: What performance cost does wrapping objects in Proxy typically add?