JavaScript Object Accessors


JavaScript Accessors (Getters and Setters)

ECMAScript 5, also known as ES5 in 2009, brought in Getter and Setters.

Getters and setters help you create Computed Properties for Objects.


JavaScript Getter (The get Keyword)

This illustration employs a lang attribute to getthe value associated with the language attribute.


JavaScript Setter (The set Keyword)

This sample demonstrates using a lang attribute to set a value to the language property.


JavaScript Function or Getter?

What makes these two examples different from each other?

Example 1: To get the full name, use the function like this - person.fullName().

Example 2: Retrieve the full name as a property using person.fullName.

The second example has a more straightforward way of writing.


Data Quality

JavaScript helps improve the quality of data by using getters and setters.

With the lang property in this example, the result is the uppercase version of the language property.

By utilizing the lang property in this instance, an uppercase value is stored in the language property.


Why Using Getters and Setters?

  • It provides an easier way to write code.
  • It permits using the same syntax for both properties and methods.
  • It can improve the quality of data.
  • It comes in handy for handling tasks in the background.

Object.defineProperty()

You can use the Object.defineProperty() method to add Getters and Setters.