This article's content
Defining object properties in JavaScript
Object.defineProperty(obj, prop, descriptor)

This method allows a precise addition to or modification of a property on an object. By default, properties added using Object.defineProperty() are not writable, not enumerable, and not configurable.

const obj = {};
Object.defineProperty(obj, 'key2', {
  configurable: false,
  enumerable: false,
  value: 'static',
  writable: false
});

const obj2 = {};
let bValue = 38;
Object.defineProperty(obj2, 'b', {
  get() { return bValue; },
  set(newValue) { bValue = newValue; },
  enumerable: true,
  configurable: true
});

Data descriptor vs accessor descriptor

A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys:

Descriptiondefault when using definePropertydefault when using const obj = {}
configurableif false, then the type of this property cannot be changed between data property and accessor property, the property may not be deleted, other attributes of its descriptor cannot be changed, however, if it’s a data descriptor with writable: true, the value can be changed, and writable can be changed to falsefalsetrue
enumerableWhether the property shall appear during for...in loop or Object.keys method and whether the property is picked by Object.assign() or spread operator. You can check with myObj.propertyIsEnumerable('a')falsetrue
valueany valid JavaScript valueundefined
writableif property can be changed with obj.foo = "new";falsetrue
getAccessor descriptor only. A function which serves as a getter for the property, or undefined if there is no getter.
setAccessor descriptor only. A function which serves as a setter for the property, or undefined if there is no setter.

If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both [value or writable] and [get or set] keys, an exception is thrown.

More examples on the MDN website.

Object descriptors in decorators

Object descriptors play an important role in TypeScript decorators.

About Author

Mathias Bothe To my job profile

I am Mathias, born 40 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 16 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of bosy.com, creator of the security service platform BosyProtect© and initiator of several other software projects.