Open In App

How to get property descriptors of an object in JavaScript ?

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:

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.




<script>
  
    // Object
    const Obj = {
        property1: "GeeksforGeeks",
        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: GeeksforGeeks
  
    console.log(descriptor2.value);
    // expected output: 12
  
</script>

Output:

true
true
GeeksforGeeks
12

Descriptors:

A property descriptor of an object consists of some of the following attributes to define each property:

Example: The below example describes the property attributes for property1 and property2 related to object Obj.




<script>
    const Obj = {
        property1: "GeeksforGeeks",
        property2: 12
    };
  
    const descriptor1 = Object
        .getOwnPropertyDescriptor(Obj, 'property1');
  
    const descriptor2 = Object
        .getOwnPropertyDescriptor(Obj, 'property2');
  
    console.log(descriptor1);
    console.log(descriptor2);
</script>

Output:

{value: 'GeeksforGeeks', writable: true, enumerable: true, configurable: true}
    configurable: true
    enumerable: true
    value: "GeeksforGeeks"
    writable: true
    [[Prototype]]: Object

{value: 12, writable: true, enumerable: true, configurable: true}
    configurable: true
    enumerable: true
    value: 12
    writable: true
    [[Prototype]]: Object

Article Tags :