Proxy vs. Reflect in JavaScript

Quick primer on JavaScript metaprogramming concepts—Proxy and Reflect—with background, practical examples, and references.

Mar 16, 2021 · 2 min read · 242 Words · -Views -Comments · Programming
JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Proxy rarely shows up in day-to-day frontend code, but that doesn’t mean it lacks value. We just don’t reach for it often. Here’s a refresher to keep it in mind.

Metaprogramming

MDN groups Proxy and Reflect under the metaprogramming umbrella. What does that mean?

Metaprogramming is the practice of writing programs that treat other programs (or themselves) as data—modifying them or performing compile-time work at runtime. Compared with hand-writing every behavior, metaprogramming can boost productivity or provide more flexibility without recompilation.

(Source: Wikipedia.) In other words, metaprogramming is a language-agnostic concept—not unique to JavaScript.

https://static.1991421.cn/2021/2021-03-17-225913.jpeg

(Graphic from https://draveness.me/metaprogramming/)

Proxy and Reflect

As the name suggests, Proxy lets us intercept operations such as get, set, or construct on a target object. Why is that useful? We can transform values, guard access, or observe behavior without touching the original object.

Example:

const user = { firstname: 'alan' };

const userProxy = new Proxy(user, {
  get(target, prop) {
    return target[prop] ? target[prop] : `get prop ${prop} missing`;
  },
  set(target, prop, value) {
    console.log(`set prop ${prop} as ${value}`);
    target[prop] = value;
  }
});

console.log(userProxy.lastname); // get prop lastname missing

Accessing a missing property returns a custom message; setting a value logs a message before delegating to the original object. You get a clean interception layer without polluting user itself.

Another use case: two-way data binding in form UIs. A proxy can sit between the UI and the underlying state, syncing updates in both directions.

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover