What Is an Object Property Descriptor in JavaScript?

Object property descriptors are attributes that describe the configuration of a specific object property. For example, to create an object property "foo" that does not appear in enumeration of object's properties you would set the enumeration descriptor as false like so:

const obj = { bar: 'baz' };
const objDescriptor = { value: 'bar', enumerable: false };

Object.defineProperty(obj, 'foo', objDescriptor);

for (const prop in obj) {
    console.log(prop); // 'bar'

Based on the property descriptors, an object property can be concluded as being either a data property or an accessor property. Both data and accessor property descriptors are objects that have the following keys/descriptors in common:

  • enumerable — if true, the property will show up during enumeration of the object properties;
  • configurable — if false, it prevents deletion of the property as well as any changes to the object property's descriptors.

In addition to those, a data property has the following descriptors:

  • value — any value that's associated with the property;
  • writable — if true, the property value can be reassigned.

In contrast, an accessor property has the following descriptors in addition to the common ones between the two:

  • get — a getter function for the property;
  • set — a setter function for the property.

You can use the following methods to specify data and accessor property descriptors:

  • Object.create() — used to create a new object (using an existing object as the prototype of the newly created object); it allows specifying data descriptors for each property you add to the object;
  • Object.defineProperty() — used to define (or modify) a single object property with option to specify data descriptors;
  • Object.defineProperties() — used to define (or modify) multiple object properties with option to specify data descriptors.

You can use the following methods to get details of data and accessor property descriptors:

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.