Close

Obtaining Property Descriptor by using Object.getOwnPropertyDescriptor()

[Updated: Mar 1, 2019, Created: Mar 1, 2019]

The Object.getOwnPropertyDescriptor(object, property) method returns a 'property descriptor' of the specified property.

What is Property Descriptor?

A 'property descriptor' is an object which describes following attributes of the target property:

  • value: The value of the property.
  • writable: Can property be changed? (true/false).
  • configurable: Can property be changed and deleted? (true/false).
  • enumerable: Can property be looped over? (true/false).
  • get: The corresponding getter method of the property. If there's no getter then it is undefined.
  • set: The corresponding setter method of the property. If there's no setter then it is undefined.

Examples

const person = { name: 'Joe' };
let propertyDescriptor = Object.getOwnPropertyDescriptor(person, 'name');
console.log(propertyDescriptor);
const person = { get name() { return 'Joe'; } };
let propertyDescriptor = Object.getOwnPropertyDescriptor(person, 'name');
console.log(propertyDescriptor);
console.log(propertyDescriptor.get);
console.log(propertyDescriptor.get());
const person = {
    set name(nm) {}
};
let propertyDescriptor = Object.getOwnPropertyDescriptor(person, 'name');
console.log(propertyDescriptor);
console.log(propertyDescriptor.set);
const person = {
    set name(nm) {},
    get name() {}
};
let propertyDescriptor = Object.getOwnPropertyDescriptor(person, 'name');
console.log(propertyDescriptor);
console.log(propertyDescriptor.set);
console.log(propertyDescriptor.get);
class Employee {
    constructor(name, dept) {
        this.name = name;
        this.dept = dept;
    }

}
let pd = Object.getOwnPropertyDescriptor(new Employee('Tina', 'IT'), 'name');
console.log(pd);

See Also