Javascript property descriptors explained

Photo by Nubelson Fernandes on Unsplash

Property descriptors are a fundamental, yet often overlooked, aspect of JavaScript. They give developers control over property behavior at a granular level. This article will explore what property descriptors are, how they work, and how you can use them to fine-tune object properties in JavaScript.

What is a Property Descriptor?

A property descriptor is an object that describes the behavior of a specific property on an object. It provides information about the property’s value and its writability, enumerability, and configurability.

Attributes of a Property Descriptor

There are four main attributes in a property descriptor:

  • writable: Determines whether the property’s value can be changed.
  • enumerable: Defines whether the property will be returned in a loop using for...in or Object.keys().
  • value: Holds the current value of the property.
  • configurable: Indicates if the type of descriptor can be changed and if the property can be deleted from the corresponding object.

Default Descriptors

Every property has a descriptor with default settings, which can be inspected using Object.getOwnPropertyDescriptor(). By default, for properties created directly on an object, these attributes are set to true.

let car = { make: 'Honda', year: 2000 };

let descriptor = Object.getOwnPropertyDescriptor(car, 'make');

console.log(descriptor);

// Output: { value: 'Honda', writable: true, enumerable: true, configurable: true }

Modifying Descriptors

JavaScript also allows us to change these descriptors using Object.defineProperty(). This can be used to make properties read-only, hide them from enumeration, or prevent them from being deleted or reconfigured.

Object.defineProperty(car, 'make', { writable: false });
// 'make' property is now read-only

Practical Applications of Property Descriptors

Understanding property descriptors can be particularly useful when you want to:

  • Create constants on an object (by setting writable: false).
  • Hide internal properties from the output when iterating over properties (by setting enumerable: false).
  • Protect the structure of an object by preventing extensions or deletions (by setting configurable: false).

Conclusion

Property descriptors are a powerful feature in JavaScript that allow for precise control over how properties behave. By understanding and using property descriptors effectively, developers can write more robust and secure code, safeguarding the integrity of their objects and ensuring that they behave exactly as intended.

,