Object property descriptors
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.
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:
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:
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:
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: