DEV Community

Lars Graubner
Lars Graubner

Posted on • Originally published at larsgraubner.com on

A practical use case for a JavaScript Proxy

When JavaScript Proxies were introduced I was excited. It sounded like a nice feature, but after all I was lacking any practical use cases. Until now! Some days ago I was refactoring some code and came across an object which had upper cased keys for it’s content. I really wanted to make them lower case for consistency, but those keys also exist on users devices local state. So just changing them in the codebase would break it for them. To switch to lower case keys anyways I remembered JavaScript Proxy.

With JavaScript Proxy you can hook into objects getter and setter mechanism. So my idea was to make an Proxy to access object values with case insensitive keys. That’s actually really ease to implement:

function caseInsensitive(target) {
  return new Proxy(target, {
    get: (obj, key) => obj[key.toLowerCase()]
    set: (obj, key, value) => {
      obj[key.toLowerCase()] = value
      // required, see https://lrs.link/proxy
      return true
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

As you can see the getters and setters just lower case any key used to access the object. This way all of the following works:

const animals = caseInsensitive({
  species: 'monkey'
})

animals['SPECIES'] // monkey

animals['SpEcIeS'] = 'giraffe'
animals['species']// giraffe
Enter fullscreen mode Exit fullscreen mode

Simple, but effective this suits my needs. Finally I can say I have used JavaScript proxies to solve a problem. If you know any other use cases let me know in the comments!

Top comments (0)