Discovering the Power of JavaScript Proxy After All This Time

marclipovsky

Marc Lipovsky

Posted on April 26, 2023

Discovering the Power of JavaScript Proxy After All This Time

As an engineer who has spent most of my time in JavaScript for over 25 years, I thought I had seen it all. I've conquered callbacks, made friends with promises, and even tamed the mighty async-await beast. Yet, one day, I stumbled upon a hidden gem I had never used before: the JavaScript Proxy.

It took me a quarter of a century to discover this versatile and powerful feature that has been sitting there, waiting to be unveiled. So, if you're like me and have overlooked JavaScript Proxy all these years, allow me to show you some intriguing use cases that might just change the way you write JavaScript.

1. Validation

Have you ever felt the need to put a leash on your object's properties to ensure data integrity? With Proxies, you can add validation checks when setting property values. It's like having a personal bodyguard for your data!

const validationHandler = {
  set: function (target, property, value) {
    if (property === 'age' && (typeof value !== 'number' || value <= 0)) {
      throw new TypeError('Age must be a positive number');
    }
    target[property] = value;
    return true;
  },
};

const person = new Proxy({}, validationHandler);
person.age = 25; // OK
person.age = -5; // Throws TypeError
Enter fullscreen mode Exit fullscreen mode

2. Logging and profiling

Debugging can often feel like searching for a needle in a haystack. Why not let Proxies lend you a hand by logging or profiling operations on your objects? It's like having your very own private investigator!

const loggingHandler = {
  get: function (target, property) {
    console.log(`Getting ${property}`);
    return target[property];
  },
  set: function (target, property, value) {
    console.log(`Setting ${property} to ${value}`);
    target[property] = value;
    return true;
  },
};

const loggedObject = new Proxy({}, loggingHandler);
loggedObject.foo = 42; // Logs: "Setting foo to 42"
console.log(loggedObject.foo); // Logs: "Getting foo" and 42
Enter fullscreen mode Exit fullscreen mode

3. Access control

Protect your object's properties like Fort Knox by enforcing access control. With Proxies, you can make certain properties read-only or restrict access based on specific conditions. It's like having an impenetrable security system!

const readOnlyHandler = {
  set: function (target, property, value) {
    if (property === 'readOnly') {
      throw new Error('Cannot modify read-only property');
    }
    target[property] = value;
    return true;
  },
};

const protectedObject = new Proxy({ readOnly: true }, readOnlyHandler);
protectedObject.newProperty = 'some value'; // OK
protectedObject.readOnly = false; // Throws Error
Enter fullscreen mode Exit fullscreen mode

4. Lazy loading

Why do all the hard work upfront when you can take it easy? Proxies enable you to implement lazy loading of object properties, only computing or fetching values when they're actually accessed. It's like having a personal assistant to manage your workload!

const lazyLoadHandler = {
  get: function (target, property) {
    if (!target[property]) {
      target[property] = expensiveComputation();
    }
    return target[property];
  },
};

const lazyLoadedObject = new Proxy({}, lazyLoadHandler);
const result = lazyLoadedObject.expensiveProperty; // Calls expensiveComputation() on first access
Enter fullscreen mode Exit fullscreen mode

5. Computed properties

Transform your objects into clever mathematicians by creating computed properties. Proxies let you compute values based on other properties, making your objects smarter and more flexible. It's like having a built-in calculator!

const computedHandler = {
  get: function (target, property) {
    if (property === 'fullName') {
      return `${target.firstName} ${target.lastName}`;
    }
    return target[property];
  },
};

const user = new Proxy({ firstName: 'John', lastName: 'Doe' }, computedHandler);
console.log(user.fullName); // Logs: "John Doe"
Enter fullscreen mode Exit fullscreen mode

So there you have it, folks! After 25 years of being a JavaScript aficionado, I have finally come to appreciate the power and versatility of JavaScript Proxy (MDN). It's never too late to learn something new and add a shiny tool to your developer toolbox!

Now, it's your turn! How have you used JavaScript Proxy in your projects? Share your creative and innovative use cases in the comments section below. Let's embark on this Proxy journey together and see where it takes us!

💖 💪 🙅 🚩
marclipovsky
Marc Lipovsky

Posted on April 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related