Mastering JavaScript Property Descriptors: A Step-by-Step Guide

Unlocking the Power of JavaScript Objects

Getting to Know Property Descriptors

When working with JavaScript objects, understanding property descriptors is crucial. A property descriptor is an object that describes a property of another object, providing valuable information about its behavior and characteristics. To access these descriptors, JavaScript provides the Object.getOwnPropertyDescriptor() method.

The Syntax

This static method is part of the Object class and requires two parameters: obj (the object containing the property) and prop (the name or Symbol of the property whose description is to be retrieved). The syntax is straightforward:

Object.getOwnPropertyDescriptor(obj, prop)

What to Expect

The getOwnPropertyDescriptor() method returns a property descriptor object for the specified property of the given object. If the property doesn’t exist, it returns undefined.

A Closer Look

Let’s explore an example to see how this method works. Suppose we have an object obj with two properties: x with a value of 711 and a getter function number() that returns the value of x. We can use getOwnPropertyDescriptor() to retrieve the property descriptors for both x and number().

const obj = {
  x: 711,
  get number() {
    return this.x;
  }
};

console.log(Object.getOwnPropertyDescriptor(obj, 'x'));
console.log(Object.getOwnPropertyDescriptor(obj, 'number'));

Defining Properties with defineProperty()

But what if we want to define a property programmatically? That’s where defineProperty() comes in. Let’s create an empty object obj and add a property id using defineProperty(). Then, we’ll use getOwnPropertyDescriptor() to retrieve the property descriptor for id.

const obj = {};

Object.defineProperty(obj, 'id', {
  value: 123,
  writable: true,
  enumerable: true,
  configurable: true
});

console.log(Object.getOwnPropertyDescriptor(obj, 'id'));

As you can see, getOwnPropertyDescriptor() returns the same property descriptors we defined using defineProperty(). This powerful combination allows you to take full control of your JavaScript objects.

By Alex Rivers

I write hands-on guides to web development and programming: JavaScript and React patterns, Python scripting, CSS layout and the developer tools that tie it all together. I like explanations that start with working code and end with knowing why it works. If a post saves you an afternoon of debugging, it did its job.