Property Descriptor in JavaScript

JavaScript gives us control to define, modify, and configure properties. This is made possible using a property descriptor object, which has the following attributes:

- value 

- writable 

- configurable 

- enumerable 

When we define a property on an object as follows:

var car = {

_doors: 4

};

The property descriptor's value attribute is set to 4, writable (which controls if we can write values to an object property) is set to true, configurable (which controls if we can delete a property) is set to true, and enumerable (which controls if property can be enumerated) is also set to true. We can check these attributes as follows:

var desc = Object.getOwnPropertyDescriptor (car, '_doors');

alert(desc.writable); // true

alert(desc.configurable); // true

alert(desc.value); // 4

alert(desc.enumerable); // true

Another important thing to keep in mind that Object.getOwnPropertyDescriptor works only on 'own' properties and not on 'prototype' properties. Furthermore, we can set all these property descriptor attributes using the Object.defineProperty() as follows:

Object.defineProperty (car, 'name', {

value: 'Audi',

writable: true

});

var desc = Object.getOwnPropertyDescriptor (car, 'name');

alert(car.name);

alert(desc.writable);

alert(desc.enumerable); // If you don't specify it, it defaults to false

alert(desc.configurable); // Didn't specify, so defaults to false

If we don't specify the value of attributes in Object.defineProperty(), they default to false, and that's one important thing to keep in mind. Complete code is given below: