Javascript - Get Property Descriptor

Introduction

To get the property descriptor for a given property, use Object.getOwnPropertyDescriptor() method.

This method accepts two arguments:

  • the object and
  • the name of the property.

The return value is an object with properties:

  • configurable, enumerable, get, and set for accessor properties or
  • configurable, enumerable, writable, and value for data properties.
var book = {};

Object.defineProperties(book, {

   _year: {
      value: 2018
  },

  edition: {
      value: 1
  },

  year: {
      get: function(){
          return this._year;
      },

      set: function(newValue){
          if (newValue > 2018) {
              this._year = newValue;
                this.edition += newValue - 2018;
            }
        }
    }
});

var descriptor = Object.getOwnPropertyDescriptor(book, "_year");
console.log(descriptor.value);          //2018
console.log(descriptor.configurable);   //false
console.log(typeof descriptor.get);     //"undefined"

var descriptor = Object.getOwnPropertyDescriptor(book, "year");
console.log(descriptor.value);          //undefined
console.log(descriptor.enumerable);     //false
console.log(typeof descriptor.get);     //"function"