Object.defineProperty
You'll learn how to define or modify a single object property with fine-grained control over its behavior.
What Is Object.defineProperty?
While you can add or update properties using dot or bracket notation, Object.defineProperty() gives you surgical precision. It lets you create or modify a property while explicitly setting its descriptor attributes: writable, enumerable, and configurable.
Think of regular property assignment as hanging a picture on your wall with tape—it works, but you have limited control. Object.defineProperty() is like using a professional mounting system where you can control exactly how that picture behaves on the wall.
The Syntax
Object.defineProperty(object, propertyName, descriptor);
- object: The object you're modifying
- propertyName: The property key (as a string)
- descriptor: An object specifying the property's attributes
Basic Example
const user = {};
Object.defineProperty(user, 'id', {
value: 12345,
writable: false,
enumerable: true,
configurable: false
});
console.log(user.id); // 12345
user.id = 99999; // Fails silently (or throws in strict mode)
console.log(user.id); // Still 12345
When to Use This
Use Object.defineProperty() when you need to:
- Create read-only properties
- Hide properties from enumeration (like
for...in) - Prevent properties from being deleted or reconfigured
- Define properties on objects where regular assignment isn't expressive enough
Key Takeaway: Object.defineProperty() lets you define or modify a single property with explicit control over whether it can be changed, enumerated, or deleted—giving you precise control beyond simple assignment.