0Pricing
JavaScript Academy · Lesson

Practical Proxy Use Cases

Build validation, logging, and reactive objects.

Proxies in Practice

Now you will combine proxies and Reflect to solve real problems: validation, logging, default values, and more. Each pattern wraps a plain object without changing it.

Validation Wrapper

Enforce a schema: reject any write that fails a rule. The target stays clean because bad data never lands.

function validated(obj, rules) {
  return new Proxy(obj, {
    set(target, prop, value, receiver) {
      const rule = rules[prop];
      if (rule && !rule(value)) {
        throw new TypeError('invalid value for ' + prop);
      }
      return Reflect.set(target, prop, value, receiver);
    }
  });
}

const user = validated({}, { age: v => v >= 0 });
user.age = 25;
console.log(user.age);
try { user.age = -1; } catch (e) { console.log(e.message); }

All lessons in this course

  1. Creating a Proxy
  2. get and set Traps
  3. The Reflect API
  4. Practical Proxy Use Cases
← Back to JavaScript Academy