In JavaScript, almost everything is an Object
This said, it's very important to understand the mechanics of objects in detail to get the best out of JavaScript. Hence today, I'll try to discuss something called as Object Property Descriptors, if you haven't heard it yet, get ready to learn something interesting here.
As a recap, Object is a collection of key-value pairs. Simple yet powerful as it can used to store any complex data and easily accessible. It is widely used in our day-to-day use cases. Beyond key-value, JavaScript also offers what are known as property descriptors.
Property Descriptors
Property descriptor gives use more insight about a property beyond it's value. Now with an example let's see how to access these properties.
var person = {
name: "John",
age: "20"
}
Object.getOwnPropertyDescriptor(person, 'name');
/* It gives us
{
configurable: true,
enumerable: true,
value: "foo",
writable: true
}
*/
- value - This holds the value of the key
- writable - default
true
, indicates if the property's value can be changed or not. - enumerable - default
true
, indicates if the property will appear in looping - configurable - default
true
, indicates if the descriptor properties can be changed
So, now that we know how to read these properties, let's see how to set these properties.
Writable
var person = {
name: "John",
age: "20"
}
Object.defineProperty(person, "name", {
writable: false
});
person.name = "Smith"; //This will cause an error in the strict mode
// Error: Cannot assign to read only property 'name'
// In non strict mode - no error occurs, but the value shall not be updated
person.name // John
Enumerable
Let's add a property sayHello to the person object
var person = {
name: "John",
age: "20"
sayHello(){
console.log("Hello ", this.name);
}
}
for(key in person){
console.log(key) // name, age, sayHello
}
/*set the sayHello as non enumerable */
Object.defineProperty(person, "sayHello", {
enumerable: false
});
for(key in person){
console.log(key) // name, age
}
Configurable
Commonly used for built in Object, this restricts further more alterations to be done on property descriptors for an property. Example: prototype property is non configurable.
Object.getOwnPropertyDescriptor(Array, 'prototype');
// configurable - false
Warning: Once an property is set as non configurable, it cannot be undone.
Methods Object.defineProperties
and Object.getOwnPropertyDescriptors
allows us to get and set all the property descriptors of an object at once.
Now that we understand these abilities that JavaScript provides us to have more control over Object properties, you could also read about Object.freeze
and Object.seal
and experiment on how the property descriptors change on applying these methods.
Happy coding! ✨
If you found this article useful follow me on LinkedIn & Twitter to be part of my journey.