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.
The Proxy object wraps another object and intercepts fundamental operations (like reading properties, writing values, or function calls) using Traps.
Proxies power modern reactive frontend frameworks (like Vue 3 and MobX), input validation layers, and auto-logging stores.
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"
userProxy.age = 30; // Works cleanly!
// userProxy.age = "thirty"; // Throws TypeError: Age must be a number!
targetUser instead of userProxy bypasses all proxy traps! Always interact through the proxy instance.Write it yourself. The tests below run against your code.
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!
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.
`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.
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.