What are JavaScript object getters and setters for?
TL;DR
JavaScript object getters and setters are used to control access to an object's properties. They provide a way to encapsulate the implementation details of a property and define custom behavior when getting or setting its value.
Getters and setters are defined using the get
and set
keywords, respectively, followed by a function that is executed when the property is accessed or assigned a new value.
Here's a code example demonstrating the use of getters and setters:
JavaScript object getters and setters
In JavaScript, getters and setters are special methods that allow you to control how properties of an object are accessed and modified.
- Getters: Functions that are invoked whenever you try to access a property using dot notation (e.g.,
obj.name
). They provide a way to customize the value that is returned when the property is read. - Setters: Functions that are called when you try to assign a value to a property using dot notation with the assignment operator (e.g.,
obj.name = "John"
). They allow you to perform actions like data validation, formatting, or side effects before the actual value is stored in the object.
In this example, the fullName
property doesn't have a direct value stored in the object. The getter function calculates it by combining the _firstName
and _lastName
properties. The setter splits the assigned value into first and last names and updates the internal properties accordingly.
Benefits
Getters and setters provide several benefits:
- Encapsulation: They allow you to encapsulate the implementation details of a property, making it easier to change the internal representation without affecting external code that uses the property.
- Data validation: Setters can be used to validate the values being assigned to a property, ensuring data integrity and consistency.
- Computed Properties: Getters can be used to compute and return a derived value based on other properties or calculations.
- Side effects: Setters can be used to perform side effects when a property is changed. For example, you might update a related property or trigger an action when a specific value is assigned/modified, such as logging or debugging.