Hello again! Let's continue our exploration of metaprogramming with Proxies.
In our last lesson, we established the core concept of a Proxy: a wrapper around a target object that intercepts fundamental operations using a handler containing "traps". We saw how the get and set traps correspond to the [[Get]] and [[Set]] internal methods, and we established the best practice of using Reflect to forward these operations.
Today, we'll apply this knowledge to one of the most common and powerful use cases for Proxies. Your learning goal is to implement validation and type-checking for object properties using get and set traps. This technique allows you to enforce data integrity and business rules directly at the object level, creating more robust and predictable code.
1. The set Trap: Your First Line of Defense
When implementing validation, the set trap is your most important tool. It intercepts property assignments, giving you the perfect opportunity to inspect a value before it's assigned to the target object. This allows you to reject invalid data before it can corrupt your object's state.
A set trap receives four arguments: target, property, value, and receiver. For validation, we are primarily interested in property and value. The logic is straightforward:
- Check if the
propertyandvaluemeet your criteria. - If they don't, throw an
Error(e.g.,TypeError,RangeError). This halts the assignment. - If they do, perform the assignment using
Reflect.set()and return its result.
Let's look at a canonical example of this pattern.
Proxy - JavaScript - MDN Web Docs - Mozilla
The MDN Web Docs provide a clear and concise example of using a set trap for validation. This will serve as our foundational pattern.
Read the "Validation" section. Pay close attention to how the set trap checks the property name (prop === "age") and then validates the value using Number.isInteger() and a range check.
Here's the code from that example, slightly adapted to use Reflect.set for forwarding, which is our established best practice:
const validator = {
set(target, property, value, receiver) {
if (property === 'age') {
if (!Number.isInteger(value)) {
throw new TypeError('The age is not an integer');
}
if (value < 0 || value > 200) {
throw new RangeError('The age seems invalid');
}
}
// If validation passes, forward the assignment to the target
// Reflect.set returns true on success, which satisfies the trap's requirement.
return Reflect.set(target, property, value, receiver);
},
};
const person = new Proxy({}, validator);
person.age = 100;
console.log(person.age); // 100
// These next two lines will throw errors and halt execution.
try {
person.age = 'young';
} catch(e) {
console.error(e.message); // "The age is not an integer"
}
try {
person.age = 300;
} catch(e) {
console.error(e.message); // "The age seems invalid"
}
This pattern is incredibly powerful because the validation logic is co-located with the object's definition, rather than being scattered across various functions that might modify the object.
2. Validation in Action: A Video Walkthrough
Let's watch a short video that walks through a similar validation scenario. As you watch, pay attention to the control flow inside the set trap.
Proxies (ES6) - Beau teaches JavaScript
This clip from freeCodeCamp.org demonstrates building a set trap to validate an age property. It's a good reinforcement of the pattern we just saw.
Watch from 03:28 to 06:31. The narrator makes an interesting choice: he logs an error but still allows the assignment to proceed. In a real application, we would throw an error to prevent this, just as we did in our code above.
The video highlights a critical point: if you don't explicitly throw an error or return false from the set trap, the invalid assignment might still happen. Your validation logic must be authoritative and halt the operation when rules are violated.
3. Validating Beyond Simple Objects: The Case of Arrays
Proxies aren't limited to plain objects. You can wrap any object, including built-in ones like Array. This allows for some elegant solutions. For instance, what if you wanted an array that could only contain numbers?
Your first thought might be to create a custom class that wraps the push and unshift methods. With a Proxy, the solution is far more fundamental and robust.
The javascript.info article has an excellent section on this exact problem. It reveals a key insight about how array methods work under the hood.
Read the section titled "Validation with βsetβ trap". Focus on the explanation for why you don't need to intercept methods like push. This is because these methods internally use the [[Set]] operation, which our trap already intercepts.
This insight is a great example of the power of metaprogramming. By intercepting a fundamental operation, you automatically cover all the different methods and syntax that rely on it.
Test your understanding!
Create a proxy for a user object. The set trap should enforce the following rules:
- The
usernameproperty must be a string with a length of at least 3. - The
emailproperty must be a string containing an@symbol. - Any other property can be set without validation.
Throw a TypeError with an appropriate message if a rule is violated.
Show answer
const userValidator = {
set(target, property, value, receiver) {
if (property === 'username') {
if (typeof value !== 'string' || value.length < 3) {
throw new TypeError('Username must be a string of at least 3 characters.');
}
}
if (property === 'email') {
if (typeof value !== 'string' || !value.includes('@')) {
throw new TypeError('Please provide a valid email address.');
}
}
// All good, proceed with assignment
return Reflect.set(target, property, value, receiver);
}
};
const user = new Proxy({}, userValidator);
user.username = 'alex'; // OK
user.email = 'alex@example.com'; // OK
try {
user.username = 'al'; // Throws error
} catch (e) {
console.error(e.message);
}
try {
user.email = 'invalid-email'; // Throws error
} catch (e) {
console.error(e.message);
}
4. Validating Property Names with get and set
So far, we've validated the value being assigned. You can also use traps to validate or control access based on the property key itself. A common use case is to enforce a convention for "private" properties, often denoted with a leading underscore (_).
Let's return to javascript.info to see how multiple traps can work together to create a protective barrier around certain properties.
Read the section "Protected properties with βdeletePropertyβ and other traps". Focus on how the get and set traps both check if prop.startsWith('_') to deny access.
By adding a simple check in both the get and set traps, you can effectively prevent external code from reading or writing to these "internal" properties, making your object's public interface clearer and safer.

5. get Trap Validation: A Different Approach
While the set trap is for proactive validation (preventing bad data from entering), the get trap can be used for reactive validation. This can be useful in specific scenarios, such as:
- Validating data that you've just received from an external source (e.g., a JSON API) and wrapped in a proxy.
- Providing default or fallback values for properties that are missing or invalid.
- Transforming data on the fly as it's being read.
Let's watch a final clip that demonstrates this concept.
In this video, Steve Griffith demonstrates validating data from a JSON source. He wraps each object from the source in a proxy and uses the get trap to check the age property's validity when it is accessed.
Watch from 11:31 to 19:28. Notice the workflow: an array of objects is mapped to an array of proxies. The validation logic runs inside the get trap when person.age is accessed within the try...catch block.
This approach is different but equally valid depending on your goal. Validating on set enforces a strict contract on your object from the moment of creation, while validating on get can be a way to handle and sanitize data from less predictable sources.
Test your understanding!
Create a proxy for a settings object.
- The
settrap should enforce the following:- It should only allow the properties
theme,fontSize, andshowToolbarto be set. Throw an error if any other property is assigned. - The
themeproperty must be either the string'light'or'dark'. - The
fontSizeproperty must be a number between10and24(inclusive). - The
showToolbarproperty must be a boolean.
- It should only allow the properties
- The
gettrap should:- Return a default value of
16iffontSizeis accessed but has not yet been set on the target object.
- Return a default value of
Show answer
const settingsHandler = {
set(target, property, value, receiver) {
const allowedProperties = ['theme', 'fontSize', 'showToolbar'];
if (!allowedProperties.includes(property)) {
throw new Error(`Property '${property}' cannot be set.`);
}
if (property === 'theme') {
if (value !== 'light' && value !== 'dark') {
throw new TypeError("Theme must be 'light' or 'dark'.");
}
}
if (property === 'fontSize') {
if (typeof value !== 'number' || value < 10 || value > 24) {
throw new RangeError('Font size must be a number between 10 and 24.');
}
}
if (property === 'showToolbar') {
if (typeof value !== 'boolean') {
throw new TypeError('showToolbar must be a boolean.');
}
}
return Reflect.set(target, property, value, receiver);
},
get(target, property, receiver) {
// Check if the property exists on the target before returning a default
const exists = property in target;
if (property === 'fontSize' && !exists) {
return 16; // Default value
}
return Reflect.get(target, property, receiver);
}
};
const settings = new Proxy({}, settingsHandler);
settings.theme = 'dark'; // OK
settings.fontSize = 14; // OK
console.log(settings.fontSize); // 14
const newSettings = new Proxy({}, settingsHandler);
console.log(newSettings.fontSize); // 16 (default value)
try {
settings.layout = 'grid'; // Throws error
} catch (e) {
console.error(e.message);
}
Conclusion
You've now mastered a fundamental and highly practical application of JavaScript Proxies. By embedding validation logic within the get and set traps, you can create self-defending objects that maintain their own integrity.
Key Takeaways:
- The
settrap is the primary tool for validation, allowing you to intercept and reject invalid assignments before they happen. - Validation logic can check both the
value(type, range, format) and thepropertykey (name, existence). - To prevent an invalid assignment, throw an
Errorinside thesettrap before forwarding the operation. - Always use
Reflect.setto safely forward the assignment; it correctly handles the return value required by the trap. - The
gettrap can be used for reactive validation, data transformation on read, or providing default values for missing properties.
Next Up
We have now covered intercepting property access on objects. In the next lesson, we will expand our metaprogramming toolkit to functions and constructors. We will explore how to use the apply trap to intercept function calls and the construct trap to customize the behavior of the new operator.