Object property descriptors
Object property descriptors in JavaScript (writable, enumerable, configurable)
Object property descriptors in JavaScript (writable, enumerable, configurable)
In JavaScript, every property on an object has a set of hidden attributes known as property descriptors. These control how the property is stored, modified, or displayed in the object.
There are three main descriptors: writable, enumerable, and configurable. To access or modify these properties, we use the Object.defineProperty() method.
1. writable — Whether the value can be changed
const person = {};
Object.defineProperty(person, 'name', {
value: 'Anna',
writable: false
});
person.name = 'Mariam';
console.log(person.name); // 'Anna'
Advantages of this property:
- You can prevent the value from ever being changed
- Useful for creating readonly properties
2. enumerable — Whether the property is visible in loops
const user = {};
Object.defineProperty(user, 'id', {
value: 101,
enumerable: false
});
for (let key in user) {
console.log(key); // prints nothing
}
console.log(Object.keys(user)); // []
Advantages of this property:
- Hides properties from `for...in` and `Object.keys()`
- Useful for internal/private data
3. configurable — Whether the property can be deleted or reconfigured
const settings = {};
Object.defineProperty(settings, 'theme', {
value: 'dark',
configurable: false
});
delete settings.theme;
console.log(settings.theme); // 'dark'
Object.defineProperty(settings, 'theme', {
value: 'light'
}); // Error in strict mode
Advantages of this property:
- You can lock properties to prevent their redefinition or deletion
- Useful when you need to enforce security on an object
How to view a property's descriptor
const car = { brand: 'Toyota' };
const descriptor = Object.getOwnPropertyDescriptor(car, 'brand');
console.log(descriptor);
// {
// value: 'Toyota',
// writable: true,
// enumerable: true,
// configurable: true
// }
Advantages of this method:
- You can see all three main flags
- Useful for debugging and object analysis
- 0
- 13
Comments
No comments yet. Be the first to comment!
Leave a Comment
You must be logged in to leave a comment.Login