The Secret Life of JavaScript: The Proxy
Source: Dev.to
Timothy sat at his desk, looking a bit overwhelmed. He had a simple user object, but his code was cluttered with if statements.
let user = {
name: "Timothy",
age: 25
};
// Timothy's validation code
if (user.age
“I want to protect my data,” Timothy said softly, “but I don’t want to clutter my object with validation logic in every single function. Is there a cleaner way?”
Margaret smiled warmly. She pulled a chair up next to him, not as a critic, but as a guide.
“That is a very mature instinct, Timothy,” she said. “You are looking for Metaprogramming. Specifically, a tool called the Proxy.”
The Middleman
Margaret drew a circle on the chalkboard and labeled it Target.
“Normally, when you interact with an object, you are speaking directly to it,” she explained. “The Proxy allows you to place a ‘Middleman’ in front of that object.”
const proxy = new Proxy(target, handler);
The Target is your original object. The Handler is an object that defines the rules. It contains traps that intercept your interactions.
Trap 1: Intercepting Reads (get)
“Let’s try a harmless prank to see how it works,” Margaret said. “Let’s teach the engine to lie.”
const user = { name: "Timothy" };
const handler = {
get(target, prop) {
if (prop === "name") {
return "The Great " + target[prop];
}
return target[prop];
}
};
const proxyUser = new Proxy(user, handler);
console.log(proxyUser.name); // "The Great Timothy"
Timothy’s eyes widened. “I didn’t change the object. I just changed how I read it.”
“Exactly,” Margaret nodded. “In the real world, developers use this to log data access or create ‘private’ properties. The Proxy decides what to return, not the object.”
Trap 2: Validation (set)
“Now, for your problem,” Margaret said gently. “You want to stop invalid data from ever touching your object. We can use the
settrap.”
const validator = {
set(target, prop, value) {
if (prop === "age" && value
“Precisely,” Margaret said. “You have separated your Logic (the validator) from your Data (the user). That is the hallmark of clean architecture.”
The Toolkit: Reflect and Other Traps
“Is that all it can do?” Timothy asked.
“Hardly,” Margaret laughed. “You can intercept almost anything.”
hastrap: Intercepts theinoperator (hiding keys).deletePropertytrap: Prevents properties from being deleted.applytrap: Intercepts function calls.
“And to make this easier,” she added, “we use the
ReflectAPI. It allows us to perform the default behavior without manually modifying the target.”
set(target, prop, value) {
if (value
“Thank you, Margaret,” he said. “I feel like I have superpowers. I can change how the language behaves.”
Margaret patted him on the shoulder. “You do, Timothy. But remember the Golden Rule of Metaprogramming.”
“Magic comes with a cost. Proxies add a small performance overhead to every operation. Use them for critical validation, not for every single object in your system. Use your powers for clarity, not confusion.”