Combining Getters and Setters

Getters and setters are often used together to create a property that can be accessed and modified using a straightforward syntax.

Example

let person = {
  firstName: 'John',
  lastName: 'Doe',
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  set fullName(name) {
    let parts = name.split(' ');
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

person.fullName = 'Jane Smith';
console.log(person.fullName); // Output: Jane Smith

Summary

Getters

Setters