Data Properties and Accessor Properties in JavaScript

chessboard using javascript

In JavaScript there are two type of properties: Data properties and Accessor Properties. Whenever we assign a value to a property of an object it is a data property. For example:

var person={
name:"pixxstudios"
};

So, “name” in this case is a data property. On the other hand, accessor properties rather than containing a value contains a function. So whenever we want to write a value to a property a function is called i.e. setter function and whenever we need to read a value from a property a getter function is called. For example, for the above person object we can change and retrieve the value of name property using the setter and getter function.

var person={
name:"pixxstudios",

get GetName(){
return this.name;
},

set SetName(n){
this.name=n;
}
// function names can be anything
};

So now if we try to read the value of name the get method will be called and name value will be returned and set method will be called if we try to change the value of name.

console.log(person.name); // pixxstudios

person.name="new name"; // set method called

console.log(person.name); // new name

The above example doesn’t justifies the use of accessor properties. Here are few of the reason why we should use accessor properties over data properties:

  • Triggering a behavior or doing validation whenever we need to get or set the value
  • Providing a debugging interception point for when a property changes at runtime
  • Allowing inheritors to change the semantics of how the property behaves and is exposed by overriding the getter/setter methods

NOTE: It is not compulsory to write both getter and setter for a property, either of them can also be written.

Related Posts