JavaScript Proxy Objects & Traps
Quick Overview
A Proxy sits between the code and the object, so `get` and `set` traps run on every property access. That is how observable state and validation work without modifying the original object at all.
Deep Dive
1. Metaprogramming with Proxies
The Proxy object wraps another object and intercepts fundamental operations (like reading properties, writing values, or function calls) using Traps.
2. Why It Matters
Proxies power modern reactive frontend frameworks (like Vue 3 and MobX), input validation layers, and auto-logging stores.
3. Creating a Proxy Trap
Pass the target object and a handler object containing trap functions (like get or set):
const targetUser = { name: "Alex", age: 28 };
const userProxy = new Proxy(targetUser, {
get(target, prop) {
console.log(`Property '${prop}' was read!`);
return prop in target ? target[prop] : "Not Specified";
},
set(target, prop, value) {
if (prop === "age" && typeof value !== "number") {
throw new TypeError("Age must be a number!");
}
target[prop] = value;
return true; // Return true to indicate successful assignment
},
});
console.log(userProxy.name); // Output: "Property 'name' was read!" -> "Alex"
console.log(userProxy.email); // Output: "Property 'email' was read!" -> "Not Specified"
4. Real-World Validation Guard
userProxy.age = 30; // Works cleanly!
// userProxy.age = "thirty"; // Throws TypeError: Age must be a number!
5. Common Mistakes
- Modifying Target Directly: Interacting directly with
targetUserinstead ofuserProxybypasses all proxy traps! Always interact through the proxy instance.
6. Try It Yourself
Write it yourself. The tests below run against your code.
Create Safe User Proxy with Fallback Trap
Examples
7. Next Steps
Congratulations! You've mastered all 30 foundational JavaScript Learning Bytes, from primitive data types to V8 engine execution contexts, scope chains, closures, event loop microtasks, and metaprogramming proxies!
How was this byte?
Learning Progress
30 of 30Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.