Getter and setter methods are special methods in JavaScript that are used to get and set the value of a property. Getter methods are called when the property is accessed, and setter methods are called when the property is set.
Getter and setter methods are often used to encapsulate the data in an object. This means that the data is hidden from the outside world and can only be accessed through the getter and setter methods.
The syntax for a getter method is as follows:
get property() {
// Body of the getter method
}
The property is the name of the property. The Body of the getter method is the code that is executed when the property is accessed.
The syntax for a setter method is as follows:
set property(value) {
// Body of the setter method
}
The property is the name of the property. The value is the new value of the property. The Body of the setter method is the code that is executed when the property is set.
The following code defines a class called Person with a getter and setter method for the name property: