Getters and setters allow controlled access to properties. Getters retrieve a property’s value, while setters validate and set a property’s value.

JavaScript
class Product {
  constructor(name, price) {
    this.name = name;
    this._price = price;
  }

  get price() {
    return this._price;
  }

  set price(newPrice) {
    if (newPrice > 0) {
      this._price = newPrice;
    } else {
      console.log("Price must be a positive number.");
    }
  }
}

const product = new Product("Laptop", 1500);
console.log(product.price);  // Output: 1500

product.price = 2000;        // Valid, sets price to 2000
console.log(product.price);  // Output: 2000

product.price = -300;        // Invalid, triggers error message
// Output: Price must be a positive number.

In this example:

  • The _price property is managed with get and set methods.
  • The set method checks if the price is positive before updating it.