Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Proxy — intercepting property reads and writes

Proxy creates an object that mediates operations on a target object. The handler.get and handler.set methods let you compute values when reading and control writes while respecting language invariants.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

new Proxy(target, { get(target, property, receiver) { /* return value */ }, set(target, property, value, receiver) { /* return boolean */ } })

new Proxy(target, handler) creates a separate wrapper object; it does not copy target. Operations performed directly on target bypass the traps. An absent trap forwards the corresponding operation to the target object.

Proxy handler.get, written as get(target, property, receiver), intercepts property reads and returns the value. property is a string or symbol. receiver is the operation's receiver, usually the proxy; passing it to Reflect.get(target, property, receiver) preserves the appropriate this in getters.

Proxy handler.set, written as set(target, property, value, receiver), intercepts writes. Its result is converted to a boolean: true means success and false means rejection. A rejected assignment in strict mode throws TypeError. Returning true alone does not store the value; Reflect.set(target, property, value, receiver) performs the operation and returns its result.

Traps must respect invariants: for an own, non-configurable, non-writable data property, get cannot return a different value, and set cannot report success for writing a different value. Violations throw TypeError. In the example, double is computed, and the invalid write to score is rejected.

Examples

"use strict";
const target = { score: 0 };
const proxy = new Proxy(target, {
  get(target, property, receiver) {
    if (property === "double") return target.score * 2;
    return Reflect.get(target, property, receiver);
  },
  set(target, property, value, receiver) {
    if (property === "score" && !Number.isInteger(value)) return false;
    return Reflect.set(target, property, value, receiver);
  }
});

proxy.score = 7;
console.log(proxy.score);
console.log(proxy.double);
try {
  proxy.score = 1.5;
} catch (error) {
  console.log(error.name);
}
console.log(target.score);

Result

7
14
TypeError
7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources