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:
const person = {_name: 'John Doe', // Private propertyget name() {// Getterreturn this._name;},set name(newName) {// Setterif (newName.trim().length > 0) {this._name = newName;} else {console.log('Invalid name');}},};// Accessing the name property using the getterconsole.log(person.name); // Output: 'John Doe'// Setting the name property using the setterperson.name = 'Jane Smith'; // Setter is calledconsole.log(person.name); // Output: 'Jane Smith'person.name = ''; // Setter is called, but the value is not set due to validationconsole.log(person.name); // Output: 'Jane Smith'
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.
const person = {_firstName: 'John',_lastName: 'Doe',get fullName() {return `${this._firstName} ${this._lastName}`;},set fullName(value) {const parts = value.split(' ');this._firstName = parts[0];this._lastName = parts[1];},};console.log(person.fullName); // Output: John Doeperson.fullName = 'Jane Smith';console.log(person.fullName); // Output: Jane Smith
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.