JavaScript Interview Question #188
What are Proxy and Reflect in JavaScript?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
Proxy allows code to intercept fundamental operations performed on an object, such as property access, assignment, deletion, or key enumeration. Reflect provides standardized functions corresponding to many of those internal operations.
Detailed Explanation
Proxy allows code to intercept fundamental operations performed on an object, such as property access, assignment, deletion, or key enumeration. Reflect provides standardized functions corresponding to many of those internal operations.
They can support validation, logging, reactive systems, virtualization, and metaprogramming. Proxies are powerful but can make behavior less obvious, so they should be used when interception genuinely improves the design.
Code Example
const user = { name: "Asif" };
const proxy = new Proxy(user, {
set(target, property, value) {
if (property === "name" && !value) {
throw new Error("Name is required");
}
return Reflect.set(
target,
property,
value
);
}
});
proxy.name = "M. Asif";