Practical Proxy Use Cases
Build validation, logging, and reactive objects.
Practical Proxy Use Cases is a free JavaScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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); }Logging Wrapper
Trace every read and write for debugging by forwarding through Reflect after logging.
function logged(obj) {
return new Proxy(obj, {
get(t, p, r) { console.log('GET ' + p); return Reflect.get(t, p, r); },
set(t, p, v, r) { console.log('SET ' + p + '=' + v); return Reflect.set(t, p, v, r); }
});
}
const data = logged({ count: 0 });
data.count = 5;
console.log(data.count);Default Values
Return a fallback for any missing property, so reads never yield undefined.
function withDefault(obj, fallback) {
return new Proxy(obj, {
get(t, p, r) {
return p in t ? Reflect.get(t, p, r) : fallback;
}
});
}
const scores = withDefault({ ada: 90 }, 0);
console.log(scores.ada);
console.log(scores.unknown);Negative Array Indexing
Make arrays support Python-style negative indices by translating them in a get trap.
function negIndex(arr) {
return new Proxy(arr, {
get(t, p, r) {
const i = Number(p);
if (Number.isInteger(i) && i < 0) {
return Reflect.get(t, t.length + i, r);
}
return Reflect.get(t, p, r);
}
});
}
const list = negIndex(['a', 'b', 'c']);
console.log(list[-1]);
console.log(list[0]);Read-Only View
Expose an object that can be read but never written, useful for protecting shared config.
function readonly(obj) {
return new Proxy(obj, {
set() { console.log('blocked write'); return false; },
deleteProperty() { console.log('blocked delete'); return false; }
});
}
const config = readonly({ apiUrl: '/api' });
config.apiUrl = '/hacked';
console.log(config.apiUrl);Counting Access
Track how many times each property is read by storing counts outside the target.
function counted(obj) {
const counts = {};
const proxy = new Proxy(obj, {
get(t, p, r) {
counts[p] = (counts[p] || 0) + 1;
return Reflect.get(t, p, r);
}
});
return { proxy, counts };
}
const { proxy, counts } = counted({ x: 1 });
proxy.x; proxy.x; proxy.x;
console.log(counts.x);Computed Virtual Properties
Expose derived values that are not stored, computed fresh on each read.
const rect = new Proxy({ width: 4, height: 3 }, {
get(t, p, r) {
if (p === 'area') return t.width * t.height;
return Reflect.get(t, p, r);
}
});
console.log(rect.area);
rect.width = 10;
console.log(rect.area);Throwing on Unknown Reads
Catch typos early by throwing when code reads a property that does not exist.
function strict(obj) {
return new Proxy(obj, {
get(t, p, r) {
if (typeof p === 'string' && !(p in t)) {
throw new ReferenceError('unknown property: ' + p);
}
return Reflect.get(t, p, r);
}
});
}
const o = strict({ name: 'Ada' });
console.log(o.name);
try { console.log(o.naem); } catch (e) { console.log(e.message); }Combining Concerns
Real wrappers often combine validation and logging in one handler, each trap forwarding to Reflect.
const account = new Proxy({ balance: 0 }, {
set(t, p, v, r) {
if (p === 'balance' && v < 0) throw new RangeError('no overdraft');
console.log(p + ' set to ' + v);
return Reflect.set(t, p, v, r);
}
});
account.balance = 100;
console.log(account.balance);
try { account.balance = -50; } catch (e) { console.log(e.message); }Why These Patterns Matter
Proxies add cross-cutting behavior, validation, logging, defaults, access control, without polluting the original object or its callers. This is exactly how reactive frameworks observe state changes. Use them when you need transparent interception.
const observed = new Proxy({ n: 0 }, {
set(t, p, v, r) {
const ok = Reflect.set(t, p, v, r);
console.log(p + ' is now ' + t[p]);
return ok;
}
});
observed.n = 1;
observed.n = 2;Quick Check
Which proxy trap would you use to reject invalid values before they are stored?
Recap: Practical Proxy Use Cases
You applied proxies to real problems:
- Validation in the set trap rejects bad data.
- Logging traces reads and writes via
Reflect. - Defaults and virtual properties live in the get trap.
- Read-only views, access counting, and strict typo-checking all wrap objects transparently.
Frequently asked questions
Is the “Practical Proxy Use Cases” lesson free?
Yes — the full text of “Practical Proxy Use Cases” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Practical Proxy Use Cases”?
Build validation, logging, and reactive objects. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Practical Proxy Use Cases” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating a Proxy
- get and set Traps
- The Reflect API
- Practical Proxy Use Cases