Javascript Proxy 101

What is a Proxy

Meaning “person who is deputed to represent or act for another” is from 1610s. Of things, “that which takes the place of something else,"

Getter & Setter

When handling objects, these are the methods that retrieve or modify the contents of said object.

  • These can be useful for simplifying interfaces, as it allows for equal syntax for properties & methods.
    • You don’t have to know the underlying implementation of a class, “is this a method or a property?” is a question you don’t have to ask yourself. This can reduce cognitive load when working.
const mix = {
  title: "goosebumps #44",
  link: "",

  set newLink(link) {
    this.link = link;
  },
};

mix.newLink = "example.gb44.mp3";

console.log(mix.link); // example.gb44.mp3

Now with this in mind, proxies are commonly used to modify behaviour and set off side effects in these methods. And it makes sense, when updating properties, you might want to inform other parts of your system about what happened: logs, metrics, telemetry, RPC’s, or running other code. Not limited to just this, of course

Common use cases

  • Framework authoring: MobX, SolidJS, Vue and many more
  • Native way to handle side effects, for things like logs
  • In memory cache:
const cache = {
    'John': ['55', '99']
}
const handler = {
    get: function(target, player) {
        if(target[player]) {
            return target[player]
        } else {
            fetch('some-api-url')
            .then((scoreboard) => {
                target[player] = scoreboard
                return scoreboard
            })
        }
    }
}
const proxy = new Proxy(cache, handler)
// access cache and do something with scoreboard
- https://blog.logrocket.com/practical-use-cases-for-javascript-es6-proxies/
  • Validation
  • Access control

You might not use them everyday, but knowing they exist & understanding them to some level will help you identify situations they’re useful in

Caveats and things to be aware of

  • They can complicate code, especially if used unnecessarily
  • They don’t have 100% browser coverage, but this may be negligible
  • Not as performant as native objects