Question presented to candidate: "You want to log every time a specific object's properties are read or written, without changing any of the code that actually uses that object. How would a JavaScript Proxy let you do that, and what exactly gets intercepted?"
What a strong answer should cover:
- 📌 Interview term:
Proxy— wraps a target object and intercepts fundamental operations (get,set,has,deleteProperty, and more) via trap handler functions — code using the proxy calls it exactly like the original object, with zero visible syntax difference. - 📌 Verified, not assumed: a real handler with
get/set/has/deletePropertytraps genuinely fired on every corresponding real operation — reading a property, writing one, usingin, anddeleteall genuinely triggered their matching trap function, confirmed by real, observed console output from inside each trap. - A precise answer names that a trap should genuinely delegate to the real default behavior (via
Reflect, covered in this bank's own dedicated question) unless it deliberately wants to change it — verified directly, every trap in this answer's own example correctly called the matchingReflectfunction to preserve normal behavior while adding logging on the side. - 📌 Interview term: virtualization — a genuine, real capability beyond simple logging: a
gettrap can return a value for a property that does not actually exist on the real target at all — verified directly, a realrandomIdproperty (absent from the target) genuinely worked, returning a real, different random value on each read. - A precise answer names the real, practical use cases this enables: reactive frameworks (Vue 3's reactivity system is genuinely built on Proxy), input validation (covered in this bank's own dedicated set-trap question), and lazy/computed properties (covered in this bank's own dedicated get-trap question) — all without modifying the original object's own code.
Clarifying questions expected:
- "Does the actual logging/interception need to cover every possible operation, or just reads and writes specifically?" — a real Proxy handler only needs to define the specific traps it actually cares about; undefined traps genuinely fall through to real default behavior automatically.
- "Will the proxy ever need to be compared by reference to the original object (e.g., in a Set or Map, or via ===)?" — a real, genuine Proxy is NOT reference-equal to its target, a real, sometimes-surprising detail worth confirming matters or not for the actual use case.
Code / implementation expected: Yes — a real Proxy with multiple traps, each genuinely firing on its corresponding real operation and correctly delegating to Reflect, is the concrete, convincing proof of exactly how interception works end to end.