Question presented to candidate: "If you needed to write a logging Proxy that reports every single own property key an object has, including symbol keys and non-enumerable string keys, how would you implement the ownKeys trap? Why would Object.keys or a plain for...in loop not be good enough here, and what happens if your trap forgets to include a key the target actually has?"
What a strong answer should cover:
Object.keys(),for...in, andJSON.stringifyonly ever see ENUMERABLE STRING keys — they silently skip non-enumerable string keys and skip every symbol key entirely, with no error or warning.Reflect.ownKeys()is the one method that returns everything: every own string key AND every own symbol key, enumerable or not, in the spec-defined order.- That order is not insertion order across the board — it is integer-like keys first in ascending numeric order, then remaining string keys in insertion order, then symbol keys in insertion order.
- A Proxy's
ownKeystrap should generally just returnReflect.ownKeys(target)(or something equivalent to it) rather than something ad hoc likeObject.keys(target), which would silently under-report. - The
ownKeystrap has real, spec-enforced invariants: its result must include every non-configurable own key of the target, or a realTypeErroris thrown — this is not merely a convention, it is enforced by the engine. - A
getOwnPropertyDescriptortrap usually needs to be implemented alongsideownKeys(forwarding toReflect.getOwnPropertyDescriptor), sinceObject.keysinternally calls both traps to filter down to enumerable keys.
Clarifying questions expected:
- "Does this proxy need to intercept property reads and writes too, or is enumeration the only behavior being customized?" — clarifies whether a minimal handler (just ownKeys + getOwnPropertyDescriptor) is sufficient.
- "Should the logging happen on every enumeration call, or only once when the proxy is first created?" — a real design question about where the instrumentation actually belongs.
Code / implementation expected: Yes — a real Proxy with an ownKeys trap plus a runnable test proving the real key ordering and a real invariant-violation TypeError.