logo

Getters and setters in JavaScript

June 8, 2021

In JavaScript, there are two kinds of accessors - getter and setter. Getter and setter are methods that gets and sets a property.

A getter is created by prefixing a method with the keyword get.

const user1 = {
  first: "Joe",
  last: "Smith",
  get fullName() {
    return `${this.first} ${this.last}`;
  },
};

console.log(user1.fullName); // Joe Smith

A setter is created by prefixing a method with the keyword set.

const user2 = {
  first: "Bob",
  last: "Dylan",
  get fullName() {
    return `${this.first} ${this.last}`;
  },
  set fullName(fullName) {
    [this.first, this.last] = fullName.split(" ");
  },
};

console.log(user2.first); // Bob
console.log(user2.last); // Dylan
console.log(user2.fullName); // Bob Dylan
user2.fullName = "Sarah Linsey";
console.log(user2.fullName); // Sarah Linsey