Getter and Setter in JavaScript

We can define properties on an object as follows:

var car = {

_name: 'Audi'

};

We can also configure those properties. I will soon write about how to configure the properties (e.g., whether the property should be writable or if it should be configurable, and etc.), but we can also define "getter" and "setter" on object's properties. For example, "setter" could be useful in a scenario where we would want to do some processing on the property before setting its value to something and same goes for the "getter". So, there are two ways to go about it. One way is to define "getter" and "setter" in an object itself, e.g.

Another way is to define "getter" and "setter" by using/calling the built-in Object.defineProperty (object, property, descriptor_object). Object.defineProperty method takes three parameters:

  • Object: The object whose property we want to define or configure. 
  • Property: The property on the object that we want to define or change. 
  • Descriptor object: Descriptor object allows us to configure the property and it has following attributes, namely; writable, value, get, set, configurable, and enumerable. I am going to write more about it a little later. 


 So, we can define both "getter" and "setter" using Object.defineProperty like the following:

So that's about it, for now. Let me know what do you think. Please let me know if there are any other ways to achieve the above (or, even, please feel free to suggest corrections in this post--thanks in advance).