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 h…


This content originally appeared on DEV Community and was authored by Marc Lipovsky

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

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

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

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

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"

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!


This content originally appeared on DEV Community and was authored by Marc Lipovsky


Print Share Comment Cite Upload Translate Updates
APA

Marc Lipovsky | Sciencx (2023-04-26T02:01:40+00:00) Discovering the Power of JavaScript Proxy After All This Time. Retrieved from https://www.scien.cx/2023/04/26/discovering-the-power-of-javascript-proxy-after-all-this-time/

MLA
" » Discovering the Power of JavaScript Proxy After All This Time." Marc Lipovsky | Sciencx - Wednesday April 26, 2023, https://www.scien.cx/2023/04/26/discovering-the-power-of-javascript-proxy-after-all-this-time/
HARVARD
Marc Lipovsky | Sciencx Wednesday April 26, 2023 » Discovering the Power of JavaScript Proxy After All This Time., viewed ,<https://www.scien.cx/2023/04/26/discovering-the-power-of-javascript-proxy-after-all-this-time/>
VANCOUVER
Marc Lipovsky | Sciencx - » Discovering the Power of JavaScript Proxy After All This Time. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/04/26/discovering-the-power-of-javascript-proxy-after-all-this-time/
CHICAGO
" » Discovering the Power of JavaScript Proxy After All This Time." Marc Lipovsky | Sciencx - Accessed . https://www.scien.cx/2023/04/26/discovering-the-power-of-javascript-proxy-after-all-this-time/
IEEE
" » Discovering the Power of JavaScript Proxy After All This Time." Marc Lipovsky | Sciencx [Online]. Available: https://www.scien.cx/2023/04/26/discovering-the-power-of-javascript-proxy-after-all-this-time/. [Accessed: ]
rf:citation
» Discovering the Power of JavaScript Proxy After All This Time | Marc Lipovsky | Sciencx | https://www.scien.cx/2023/04/26/discovering-the-power-of-javascript-proxy-after-all-this-time/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.