JavaScript Property Descriptors

By

Learn how JavaScript property descriptors control a property's value, writability, enumerability, configurability, getter, and setter.

~~~

Every JavaScript object property has a property descriptor.

The descriptor tells JavaScript what the property contains and how it behaves.

Use Object.getOwnPropertyDescriptor() to inspect one:

const dog = {
  breed: 'Siberian Husky'
}

const descriptor = Object.getOwnPropertyDescriptor(dog, 'breed')
console.log(descriptor)

The result is:

{
  value: 'Siberian Husky',
  writable: true,
  enumerable: true,
  configurable: true
}

These properties mean:

Define a property descriptor

Use Object.defineProperty() to create a property with the behavior you want:

const dog = {}

Object.defineProperty(dog, 'breed', {
  value: 'Siberian Husky',
  writable: false,
  enumerable: true,
  configurable: false
})

Unlike properties created with an object literal, descriptor options omitted from Object.defineProperty() default to false.

In the example, assigning a different value to dog.breed throws in strict mode. In non-strict code, JavaScript ignores the assignment.

Getter and setter descriptors

A descriptor can define a getter and setter instead of storing a value directly:

const user = {
  firstName: 'Flavio',
  lastName: 'Copes'
}

Object.defineProperty(user, 'fullName', {
  enumerable: true,
  get() {
    return `${this.firstName} ${this.lastName}`
  }
})

console.log(user.fullName)

A data descriptor uses value and writable. An accessor descriptor uses get and set. You cannot mix those two groups in the same descriptor.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about js: