In JavaScript, there are two kinds of object properties:
- Data properties
- Accessor properties
The first kind is data properties. We already know how to work with them. All properties that we’ve been using until now were data properties.
In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords:
get
- to define a getter method to get the property valueset
- to define a setter method to set the property value
Getters and Setters:
The getter works when obj.propName
is read, the setter – when it is assigned.
For example
We don’t call user.fullName
as a function, we read it normally: the getter runs behind the scenes.
As of now, fullName
has only a getter. If we attempt to assign user.fullName=
, there will be an error:
Let’s fix it by adding a setter for user.fullName
:
Why Using Getters and Setters?
- It gives simpler syntax
- It allows equal syntax for properties and methods
- It can secure better data quality
- It is useful for doing things behind-the-scenes