What are JavaScript Property Descriptors

avatar

Borislav Hadzhiev

Last updated: Feb 24, 2021

banner

Check out my new book

Property Descriptors #

A Property descriptor is an object that is meant to configure another property on another object.

The configuration options directly influence the way we work with the object properties. Some of the options we can configure are:

  • writable - whether or not the value associated with the property can be changed
  • enumerable - whether or not this property appears in for ...in loops
  • value - the current value
  • configurable - whether the property can be deleted, and whether the descriptor's properties (other than value and writable) can be changed.

Let's look at an example:

const employee = { name: 'Tom', salary: 5000, }; // {value: 'Tom', writable: true, enumerable: true, configurable: true} console.log(Object.getOwnPropertyDescriptor(employee, 'name'));

To change a property descriptor we can use Object.defineProperty:

// set the value associated with `name` as readonly Object.defineProperty(employee, 'name', {writable: false}); employee.name = 'Jim'; // {name: 'Tom', salary: 5000} console.log(employee);

In the above example we can see that by editing the descriptor to non-writable the value becomes read only.

We can also use the value config option to update the associated value:

Object.defineProperty(employee, 'salary', {value: 10000}); // {name: 'Tom', salary: 10000} console.log(employee);

We can set the config options for a property that is not yet present in the object:

Object.defineProperty(employee, 'age', {value: 50}); // {name: 'Tom', salary: 10000, age: 50} console.log(employee); // {value: 50, writable: false, enumerable: false, configurable: false} console.log(Object.getOwnPropertyDescriptor(employee, 'age'));

The default values for the property descriptors options are false, when created with Object.defineProperty, as opposed to true, when the object is simply inlined - {key: 'value'}.

We can also disable the ability to delete a property from an object:

Object.defineProperty(employee, 'title', { value: 'programmer', configurable: false, }); // {name: 'Tom', salary: 10000, age: 50, title: 'programmer'} console.log(employee); delete employee['title']; // {name: 'Tom', salary: 10000, age: 50, title: 'programmer'} console.log(employee);

Summary #

A Property descriptor is just an object that holds configuration options for a property of another object. We can set specific properties to read only, prevent them from being able to be deleted, update their values, and exclude them from for..in loops.

Use the search field on my Home Page to filter through my more than 3,000 articles.