Here, we are going to discuss the property descriptors of an Object in JavaScript. The Object.getOwnPropertyDescriptor() method returns an object describing a specific property on a given object. A JavaScript object can be created in many ways and its properties can be called by using property descriptors for that object.
Syntax:
Object.getOwnPropertyDescriptor( obj, prop )
The Object.getOwnPropertyDescriptor() takes two parameters as input as described below:
- obj: It refers to the object name whose properties are to be described.
- prop: It defines the specific property in the object whose value is to be returned.
Return value: This method returns the property of the Object if it exists else it returns undefined.
Example: In the below example, an object Obj is created which consists of two properties property1 and property2. We use Object.getOwnPropertyDescriptor() property to return the attributes and values related to each property.
JavaScript
<script> // Object const Obj = { property1: "neveropen" , property2: 12 }; const descriptor1 = Object .getOwnPropertyDescriptor(Obj, 'property1' ); const descriptor2 = Object .getOwnPropertyDescriptor(Obj, 'property2' ); console.log(descriptor1.configurable); // expected output: true console.log(descriptor1.enumerable); // expected output: true console.log(descriptor1.value); // expected output: neveropen console.log(descriptor2.value); // expected output: 12 </script> |
Output:
true true neveropen 12
Descriptors:
A property descriptor of an object consists of some of the following attributes to define each property:
- value: It is the value associated with the property that is called
- writable: It indicates if the property can be changed or not. It only returns true if the property can be manipulated
- enumerable: If the property is visible during enumeration of the properties of the corresponding object, then it returns true.
- configurable: It indicates if the property descriptor can be changed or removed from the corresponding object.
Example: The below example describes the property attributes for property1 and property2 related to object Obj.
JavaScript
<script> const Obj = { property1: "neveropen" , property2: 12 }; const descriptor1 = Object .getOwnPropertyDescriptor(Obj, 'property1' ); const descriptor2 = Object .getOwnPropertyDescriptor(Obj, 'property2' ); console.log(descriptor1); console.log(descriptor2); </script> |
Output:
{value: 'neveropen', writable: true, enumerable: true, configurable: true} configurable: true enumerable: true value: "neveropen" writable: true [[Prototype]]: Object {value: 12, writable: true, enumerable: true, configurable: true} configurable: true enumerable: true value: 12 writable: true [[Prototype]]: Object