What is getOwnPropertyDescriptor in JavaScript?

The getOwnPropertyDescriptor will return an object that has the configuration of a specific property of an object. If the property is not present in the object, undefined is returned.

Syntax

Object.getOwnPropertyDescriptor(obj, prop)

Here, obj is the object to look for the property in, and prop is the property that we want to get the description from.

Return value

This method will return an object that contains the following properties:

  • configurable: true if the value is changed and can be deleted; otherwise, false.
  • writable: true if the value can be changed.
  • enumerable: if the value can be looped in the for...in loop.
  • get: if the function is a getter function, then get will refer that function.
  • set: if the function is a setter function, then set will refer that function.
  • value: value of the property.

Code

let obj = {
num : 10,
get getNum(){ // getter
return this.num;
},
set setNum(num){ // setter
this.num = num;
}
}
Object.defineProperty(obj, "custom_prop", {
configurable: false,
enumerable : false,
writable: false,
value : "Custom value"
});
console.log("The object is ", obj);
console.log("\nPrinting Description of 'num' ")
console.log(Object.getOwnPropertyDescriptor(obj, 'num'));
console.log("\nPrinting Description of getter Fn 'getNum' ")
console.log(Object.getOwnPropertyDescriptor(obj, 'getNum'));
console.log("\nPrinting Description of setter Fn 'setNum' ")
console.log(Object.getOwnPropertyDescriptor(obj, 'setNum'));
console.log("\nPrinting Description of 'custom_prop' ")
console.log(Object.getOwnPropertyDescriptor(obj, 'custom_prop'));

In the code above, we have created an object with the getter, setter, and normal properties, a custom property (set false to writable, configurable, and enumerable), and called getOwnPropertyDescriptor on each property to get its configuration.

Free Resources