A property descriptor is an object that describes the attributes of a property. These attributes include the value of the property, whether the value of the property is writable, whether the property is enumerable, and whether the property is configurable.
As you know, there are two types of properties in JavaScript objects: data properties and accessor properties. Data properties are simple properties that do not perform any specific code when their value is read or written. On the other hand, accessor properties have get and set accessor methods that are called when the property is read or written, respectively.
Here is an example of a data property:
// descriptor for a data property called age
{
value: 19,
writable: true,
enumerable: true,
configurable: true,
}
And this is an example of an accessor property:
// descriptor for an accessor property called name
{
get: function() {
if(typeof this._name === "undefined") {
this._name = "Ali";
}
return this._name;
},
set: function(name) {
this._name = name;
},
enumerable: true,
configurable: true,
}
Each property that is defined on a JavaScript object has an associated property descriptor. Property descriptors can be obtained using Object.getOwnPropertyDescriptor and Object.getOwnPropertyDescriptors functions. They can be set using the Object.defineProperty and Object.defineProperties functions. These functions will be discussed in more detail in future posts.