Understanding Proxies in JavaScript: A Simple Guide with a To-Do List Example
When you write code, sometimes you need to control how objects behave—whether it’s tracking changes, logging access, or even preventing specific actions. This is where proxies come in!
In JavaScript, a proxy is a special object that wraps another object and allows you to control how it behaves when it is accessed. Think of it as a "middleman" that can intervene in how an object is used.
In this blog, we’ll break down what proxies are and how they work with a real-world example—a To-Do List app.
What is a Proxy?
A proxy in JavaScript is an object that wraps another object (called the target) and allows you to define custom behavior when the target object is accessed or modified. You can think of it as a "wrapper" around your object that helps you control how it behaves.
Proxies can intercept and customize:
Getting properties from an object.
Setting properties on an object.
Deleting properties from an object.
How Do Proxies Work?
To create a proxy, you use the Proxy
constructor. It requires two things:
The target object you want to wrap.
A handler object that defines the behavior (actions like reading, writing, deleting properties).
Here’s how you create a proxy:
const proxy = new Proxy(targetObject, handler);
targetObject: The original object you want to manage.
handler: An object that defines traps (functions) that control the proxy’s behavior.
Real-World Example: Tracking Actions in a To-Do List
Let’s break it down with a simple example. Imagine you’re building a To-Do List and you want to track all the actions that happen with the list, such as:
When tasks are viewed (read).
When tasks are updated (edited).
When tasks are deleted.
Using proxies, we can automatically log these actions without having to write a lot of extra code!
Step 1: Create a Basic To-Do List
Here's a simple To-Do List object:
const tasks = {
task1: "Buy groceries",
task2: "Walk the dog"
};
Step 2: Wrap the To-Do List with a Proxy
Now, let’s wrap our tasks
object with a proxy. We'll create a handler to control what happens when we interact with the tasks.
const handler = {
get(target, prop) {
console.log(`You looked at: ${prop}`); // Log when reading a task
return target[prop];
},
set(target, prop, value) {
console.log(`You updated: ${prop} to "${value}"`); // Log updates
target[prop] = value;
return true; // Indicate the set was successful
},
deleteProperty(target, prop) {
console.log(`You deleted: ${prop}`); // Log deletions
delete target[prop];
return true;
}
};
// Create the proxy that wraps the tasks object
const proxy = new Proxy(tasks, handler);
In the handler:
get
is triggered when a task is read (e.g.,proxy.task1
).set
is triggered when a task is updated (e.g.,proxy.task2 = "Walk the dog for 30 minutes"
).deleteProperty
is triggered when a task is deleted (e.g.,delete proxy.task1
).
Step 3: Interacting with the Proxy
Now let’s see what happens when you interact with the proxy.
Read a Task:
console.log(proxy.task1); // Logs: You looked at: task1
Output:
You looked at: task1
Buy groceries
Update a Task:
proxy.task2 = "Take a longer walk"; // Logs: You updated: task2 to "Take a longer walk"
Output:
You updated: task2 to "Take a longer walk"
Delete a Task:
delete proxy.task1; // Logs: You deleted: task1
Output:
You deleted: task1
Why Are Proxies Useful?
Proxies are incredibly useful because they allow you to:
Track every interaction with your object (like reading, updating, or deleting properties).
Perform custom actions based on what the user is doing with the object. For example, you can log these actions, validate input, or send data to a server.
Create more interactive and dynamic apps by automatically responding to changes and making things like real-time updates easier.
Real-World Benefits
Here are a few real-world scenarios where proxies come in handy:
Logging user actions: In applications where you want to track how users interact with your data, proxies can automatically log actions like reading or updating values.
Validation: You can use proxies to validate user input before it’s added to an object (e.g., making sure a new task is not empty).
Creating reactive apps: Proxies can be used in frameworks (like Svelte) to create reactive user interfaces where changes to data automatically update the UI.
Final Thoughts
Proxies in JavaScript are a powerful feature that let you intercept and control object behavior in a very flexible way. In our To-Do List example, we used proxies to automatically track and log actions like reading, updating, and deleting tasks.
This simple but powerful concept can be applied to all kinds of applications, whether you're building a real-time app or just want to log and monitor changes in an object.
Give proxies a try in your projects—they can save you a lot of code and give you more control over your data!