What's "Data Property" in JavaScript?

In JavaScript, a "data property" is a type of object property that has the following attributes (or property descriptors):

  • value — any value that's associated with the property;
  • writable — if true, the property value can be reassigned;
  • 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 (except value, which may be reassigned if writable is true).

These (optional) property descriptors exist for all data properties. For example, you can use the Object.getOwnPropertyDescriptor() method to check an object's descriptors like so:

const obj = {};
const descriptors = Object.getOwnPropertyDescriptor(obj, 'foo');

console.log(descriptors); // { value: undefined, writable: true, enumerable: true, configurable: true }

Here, since the "obj" does not have a property called "foo", the value descriptor is undefined whereas all other descriptors default to true. If the object property existed, it would look like so:

const obj = { foo: 'bar' };
const descriptors = Object.getOwnPropertyDescriptor(obj, 'foo');

console.log(descriptors); // { value: 'bar', writable: true, enumerable: true, configurable: true }

You can also create an object property using the Object.defineProperty() method, which would give you finer control over the property descriptors. However, you should be aware that if you use the Object.defineProperty() method (or Object.create), then all data property descriptors that you do not explicitly define, would have a default value as shown in the code below:

const obj = {};
const objDescriptor = {};

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

const descriptors = Object.getOwnPropertyDescriptor(obj, 'foo');

console.log(descriptors); // { value: undefined, writable: false, enumerable: false, configurable: false }

Since the "obj" does not have a property called "foo", the value descriptor is undefined whereas all other descriptors default to false. If the object property existed, it would look like so:

const obj = {};
const objDescriptor = { value: 'bar' };

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

const descriptors = Object.getOwnPropertyDescriptor(obj, 'foo');

console.log(descriptors); // { value: 'bar', writable: false, enumerable: false, configurable: false }

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.