Basics

In JavaScript, getters and setters are special methods that allow you to get or set the value of an object's properties.

Getters are used to get the value of an object's property. They are defined using the get keyword, followed by the name of the property, and a function to retrieve the value of the property. Here is an example of a getter in JavaScript:

class Person {
  constructor(name, age) {
    this._name = name;
    this._age = age;
  }
  
  get name() {
    return this._name;
  }
  
  get age() {
    return this._age;
  }
}

const person = new Person("Alice", 30);
console.log(person.name); // "Alice"
console.log(person.age); // 30

Setters are used to set the value of an object's property. They are defined using the set keyword, followed by the name of the property, and a function to set the value of the property. Here is an example of a setter in JavaScript:

class Person {
  constructor(name, age) {
    this._name = name;
    this._age = age;
  }
  
  get name() {
    return this._name;
  }
  
  set name(newName) {
    this._name = newName;
  }
  
  get age() {
    return this._age;
  }
  
  set age(newAge) {
    this._age = newAge;
  }
}

const person = new Person("Alice", 30);
person.name = "Bob";
console.log(person.name); // "Bob"
person.age = 35;
console.log(person.age); // 35

Getters and setters allow you to control how an object's properties are accessed and modified, and can be useful for implementing encapsulation in your code.

Last updated