This page looks best with JavaScript enabled

Property Descriptors in Javascript

 ·   ·  ☕ 2 min read

Property descriptors define property behaviour. They are attributes of the property.

Everything is an object in Javascript. Yes, I know - except those pesky things called primitives on which objects are built. We saw some (quick discussions on objects and properties)[/objects-and-props-in-javascript/] before - but I wanted to outline the descriptors further.

You can see it yourself using a simple statement.

1
2
3
4
let apple = { color: "red", size: "big" };

console.log(Object.getOwnPropertyDescriptor(apple, "color"));
// { value: 'red', writable: true, enumerable: true, configurable: true }

This is telling me what I could potentially do with color property other than seeing the value.

Following are the available property descriptors:

  • value
  • writable
  • enumerable
  • configurable
  • get
  • set

You can read attributes of the property (like what we have done above ) or set property attributes of an object by yourself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let apple = { color: "red", size: "big" };
Object.defineProperty(apple, "size", { writable: false });

console.log(Object.getOwnPropertyDescriptor(apple, "size"));
/*{value: undefined, writable: false, enumerable: false,
    configurable: false} */

apple.size = "medium";
console.log(apple); // does not change
// { color: 'red', size: 'big' }

The above example will throw an error if use strict mode is enabled. Else it fails silently. Note that only size is read-only, but you can add further attributes to the size. For e.g. apple.size.price=2

Btw, you do remember that we have to use Object.freeze() if you want to make all properties read-only, right? It can be used against specific properties as well. So the below is valid.

1
Object.freeze(apple.size);

You can also define new properties for any object and set its descriptors to your heart content.

Similarly you can use enumerate to define enumerable, or iterable property. configurable prevents certain properties from being changed or property being deleted.

Along with the properties outlined above, we also have get/set functions which are called when properties are being read or written respectively.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
let apple = { color: "red" };
Object.defineProperty(apple, "weight", {
  get: function () {
    let wt;
    this.size = "big" ? (wt = 200) : (wt = 100);
    return wt;
  },

  set: function (data) {
    if (data > 100) this.size = "big";
    else this.size = "small";
  },
});

apple.weight = "250";
console.log(apple); // does not change
// { color: 'red', size: 'big' }

get/set enable you to customize logic to fetch or write values to the specific property of the object.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things