Introduced in ECMAScript 2015 (ES6), the Proxy and Reflect APIs provide low-level metaprogramming capabilities in JavaScript. While standard objects only allow reading and writing properties, Proxy enables wrapping an object to intercept and redefine 13 fundamental language operations (termed Traps).
Every trap in a Proxy handler mirrors a corresponding static method on the built-in Reflect object:
| Proxy Trap | Intercepts | Triggered By | Reflect Method |
|---|---|---|---|
get | Property access | obj.prop, obj['prop'] | Reflect.get() |
set | Property assignment | obj.prop = val | Reflect.set() |
has | The in operator | 'prop' in obj | Reflect.has() |
deleteProperty | Deleting a property | delete obj.prop | Reflect.deleteProperty() |
apply | Function call | fn(...args), fn.apply() | Reflect.apply() |
construct | The new operator | new MyClass() | Reflect.construct() |
getPrototypeOf | Getting prototype | Object.getPrototypeOf() | Reflect.getPrototypeOf() |
setPrototypeOf | Setting prototype | Object.setPrototypeOf() | Reflect.setPrototypeOf() |
isExtensible | Extensibility check | Object.isExtensible() | Reflect.isExtensible() |
preventExtensions | Disabling extensions | Object.preventExtensions() | Reflect.preventExtensions() |
getOwnPropertyDescriptor | Inspecting descriptors | Object.getOwnPropertyDescriptor() | Reflect.getOwnPropertyDescriptor() |
defineProperty | Defining descriptors | Object.defineProperty() | Reflect.defineProperty() |
ownKeys | Enumerating keys | Object.keys(), Object.getOwnPropertyNames() | Reflect.ownKeys() |
A common beginner mistake is directly calling target[prop] inside a get trap:
The receiver parameter guarantees that if a property is a getter that uses this, this correctly points to the Proxy instance, not the underlying raw target object!
In JavaScript, arr[-1] returns undefined. We can implement Python-style negative indices using Proxy:
Proxy.revocable())A Revocable Proxy creates a proxy that can be completely disconnected and disabled at any time, instantly cutting off access:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Crash Reporting & Telemetry Buffering | Metaprogramming in JavaScript |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.