This Week I Learned #3: ES6 Proxies

I finally managed to find the time to understand what ES6 proxies are. Proxies are a spiffy feature that add some versatile metaprogramming capabilities to JavaScript. In simple terms, they enable you to modify the language-level behaviour of JavaScript objects.

With proxies, you can intercept any operations on an object, like property access, function call or instance creation using new. All you have to do is write functions. These functions, known as ‘traps’, can then be packed together in an object, known as a ‘handler’.

If that sounded Klingon to you, I wouldn’t blame you. Here’s an example that might make things clearer. Let’s say your object has a property of type Number, and you’d rather keep it that way. However, you want to allow users to set it using strings. This is how you do it using proxies:

// Your "real" object, that will be wrapped by a proxy
const target = {
  powerLevel: 9000

// The interceptor for all set operations on any property
const setTrap = (target, property, value, receiver) => {
  if (property === 'powerLevel') {
    const numericValue = Number.parseInt(value)
    if (!isNaN(numericValue)) {
      target[property] = numericValue;
    } else {
      throw new Error("KA… ME… HA… ME… HAAAAA!!")
  } else {
    target[property] = value;

// The object containing all the traps
const handler = {
  set: setTrap

// The object which will be exposed to the user
const proxy = new Proxy(target, handler)

Now, if you try to set the power level to a string which is really just a number, it will be stored as a Number type in the object:

> proxy.powerLevel = '500000'
> proxy
{ powerLevel: 500000 }

Notice how the number is printed without quotes, indicating its Number type.

However, if you try to do something funny:

> proxy.powerLevel = 'Beerus'
Error: KA… ME… HA… ME… HAAAAA!!

Pretty cool, huh? This is just a glimpse of what is possible with proxies. You can setup complex validation built right into your object. You can have real private properties. You can provide an API where your users access the object normally, and behind the scenes, you could be making an HTTP call or a database query for all they know. Sky is the limit.

If you want to know more, there is a very informative and easy-to-understand chapter called Metaprogramming with proxies in Dr Axel Rauschmayer’s excellent book, Exploring ES6. It serves both as a learning guide and a reference page for proxies.

Next week, I’ll be back with more code for thought.


2 thoughts on “This Week I Learned #3: ES6 Proxies”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s