· Jun 2024 · 3 min read

6 Use Cases for Javascript Proxies

JavaScript’s Proxy object is a powerful feature that unlocks a wide range of possibilities for developers. When combined with TypeScript, it enhances your ability to manage and manipulate objects and functions in innovative ways. This article explores the utility of Proxies through practical examples.

Introduction

JavaScript’s Proxy object is a powerful feature that unlocks a wide range of possibilities for developers. When combined with TypeScript, it enhances your ability to manage and manipulate objects and functions in innovative ways. This article explores the utility of Proxies through practical examples.

What is a Proxy?

A Proxy in JavaScript acts as a wrapper around another object, known as the target. It allows you to:

These operations include:

With a Proxy, you can inject custom logic when getting or setting properties. This capability is particularly useful for:

1. The Lazy Greeter

Ever had a friend who only says their full name when asked? That’s our lazy greeter:

let friend = new Proxy({ firstName: "Jane", lastName: "Doe" }, {  get: (person, prop) => {    if (prop === "fullName") {      return `${person.firstName} ${person.lastName}`;    }    return person[prop];  }});console.log(friend.fullName); // Output: Jane Doe

2. The Nosy Neighbor

This proxy keeps track of how many times you’ve asked about something:

let neighbor = new Proxy({ visits: 0 }, {  get: (target, prop) => {    target.visits++;    console.log(`You've asked about ${String(prop)} ${target.visits} times!`);    return target[prop];  }});neighbor.cat;neighbor.dog;neighbor.cat;

3. The Unbudging Boulder

Create an object that refuses to change, like a stubborn boulder:

function makeStubborn(obj) {  return new Proxy(obj, {    set: () => {      console.log("Nice try, but I'm not changing!");      return true;    }  });}let boulder = makeStubborn({ weight: "very heavy" });boulder.weight = "light as a feather"; // Console: Nice try, but I'm not changing!console.log(boulder.weight); // Output: very heavy

4. The Chatty Builder

A proxy that loves to talk about what it’s building:

function chattyCar() {  let car = {};  return new Proxy({}, {    get: (target, prop) => {      return (value) => {        console.log(`Ooh, adding ${value} as the ${String(prop)}!`);        car[prop] = value;        return target;      };    }  });}chattyCar().setColor("red").setWheels(4).setEngine("V8");

5. The Forgetful Library

A proxy that fetches books only when you ask for them:

let library = new Proxy({}, {  get: (shelf, book) => {    console.log(`Searching for "${String(book)}"...`);    return `Here's "${String(book)}" for you!`;  }});console.log(library.Moby_Dick);console.log(library.Pride_and_Prejudice);

6. The Strict Parent

A proxy that ensures you follow the house rules:

let kidsBedtime = new Proxy({ time: 9 }, {  set: (rules, prop, value) => {    if (prop === 'time' && (value  10)) {      console.log("Bedtime must be between 7 PM and 10 PM!");      return false;    }    rules[prop] = value;    return true;  }});kidsBedtime.time = 8; // Works finekidsBedtime.time = 11; // Console: Bedtime must be between 7 PM and 10 PM!

Extra. The Town Crier

A proxy that announces every change:

function townCrier(person) {  return new Proxy(person, {    set: (target, prop, value) => {      console.log(`Hear ye, hear ye! ${String(prop)} is now ${value}!`);      target[prop] = value;      return true;    }  });}let mayor = townCrier({ name: "Ms. Sherif" });mayor.name = "Mr. Sherif"; // Console: Hear ye, hear ye! name is now Mr. Sherif!

Remember, while proxies are super cool, they’re like superpowers — use them wisely! They can make your code slower if overused, and might confuse your teammates if you’re not careful. But when used right, they can make your JavaScript objects do amazing things!

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

6 Use Cases for Javascript Proxies 🧙 was originally published in JavaScript in Plain English on Medium, where people are continuing the conversation by highlighting and responding to this story.

More articles
Streamlining Your Dependencies with ni: A Beginner’s Tutorial to the Package Manager of the Future.
Using CSS to Implement a Dark Mode Theme for Your Websites
17 Productivity Tools for Developer Workflow Improvement