AceDevHub
Advanced JavaScript Interview QuestionsAdvancedScenario

JavaScript · Question 79

What are Proxy invariants, and why can a Proxy trap throw even when the trap itself returns a valid-looking value?

Direct answer

Proxy traps must preserve fundamental guarantees of the target object; if a trap reports a result that contradicts a non-configurable property or another protected invariant, JavaScript throws a TypeError.

Imagine a target has a non-configurable, non-writable data property id whose value is 1. A proxy cannot honestly pretend that reading that property produces an unrelated value in cases where the specification requires the target’s fixed property state to be respected. The engine validates trap results against invariants.

Similar rules apply to operations such as reporting own keys, defining properties, changing prototypes, and preventing extensions. For example, a proxy cannot hide a non-configurable own property from ownKeys merely because the handler wants a cleaner public view.

  • Invariants prevent proxies from creating object models that violate core assumptions of the language.
  • The more constrained the target becomes—especially with non-configurable properties or a non-extensible state—the fewer lies a proxy is allowed to tell.
  • When writing transparent wrappers, forwarding with Reflect reduces accidental invariant violations.