JavaScript Getter and Setter


In JavaScript, getter and setter methods are used to access and modify the properties of an object. They provide a way to encapsulate the logic for getting and setting values, allowing you to control how the properties of an object are accessed and modified. These methods are often used to validate or modify data before it is returned or updated.


1. What are Getter and Setter Methods?

  • Getter methods allow you to define how a property of an object is retrieved.
  • Setter methods allow you to define how a property of an object is set or modified.

These methods are defined using the get and set keywords in JavaScript, and they help create more robust and maintainable code.

Syntax of Getter and Setter

const obj = {
  _property: 'value',

  get property() {
    return this._property;
  },

  set property(value) {
    this._property = value;
  }
};

In this example, the property is a getter and setter for the _property. The get method retrieves the value, while the set method modifies it.


2. Using Getter and Setter in JavaScript

You can define getter and setter methods within an object to control how properties are accessed or set. These methods can be especially useful when you want to add validation or transformation logic.

Example: Using Getter and Setter

const person = {
  _firstName: '',  // Underscore used to indicate a private property

  get firstName() {
    return this._firstName;
  },

  set firstName(name) {
    if (name.length > 0) {
      this._firstName = name;
    } else {
      console.log("Please enter a valid name.");
    }
  }
};

person.firstName = "John";  // Using setter
console.log(person.firstName);  // Using getter (Output: John)

person.firstName = "";  // Trying to set an invalid value
console.log(person.firstName);  // Output: Please enter a valid name.

Explanation:

  • The _firstName property is considered private, and the firstName getter and setter control how this property is accessed and modified.
  • The setter validates the input to ensure the name is not empty before updating the _firstName.

3. Why Use Getters and Setters?

Getter and setter methods offer several benefits:

  1. Encapsulation: You can hide the internal implementation details of an object while providing a controlled way to access and modify its properties.
  2. Validation: You can include logic in the setter to validate data before setting it.
  3. Computed Properties: You can create dynamic properties that are computed based on other properties.

Example: Using Getter and Setter for Validation

const car = {
  _speed: 0,

  get speed() {
    return this._speed;
  },

  set speed(value) {
    if (value < 0) {
      console.log("Speed cannot be negative.");
    } else {
      this._speed = value;
    }
  }
};

car.speed = 50;  // Valid speed
console.log(car.speed);  // Output: 50

car.speed = -10;  // Invalid speed
console.log(car.speed);  // Output: Speed cannot be negative.

Explanation:

  • The setter method for speed ensures that the speed is never set to a negative value. If an invalid value is assigned, a message is logged.

4. Getters and Setters in ES6 Classes

In JavaScript ES6, you can also use getter and setter methods within classes to define properties and control their access. This is useful when building objects with class-based syntax, making the code cleaner and more structured.

Example: Getters and Setters in ES6 Classes

class Rectangle {
  constructor(width, height) {
    this._width = width;
    this._height = height;
  }

  get area() {
    return this._width * this._height;
  }

  set width(value) {
    if (value > 0) {
      this._width = value;
    } else {
      console.log("Width must be positive.");
    }
  }

  set height(value) {
    if (value > 0) {
      this._height = value;
    } else {
      console.log("Height must be positive.");
    }
  }
}

const rectangle = new Rectangle(10, 5);
console.log(rectangle.area);  // Output: 50 (Using getter)

rectangle.width = 15;  // Valid width
console.log(rectangle.area);  // Output: 75 (Using getter)

rectangle.height = -5;  // Invalid height (will log an error message)

Explanation:

  • In this class-based example, the getter area computes the area of the rectangle based on its width and height properties.
  • The setter methods for width and height ensure that the dimensions are positive.

5. Benefits of Using Getter and Setter

Using getter and setter methods in JavaScript offers the following advantages:

  • Encapsulation: You can keep the internal state of the object hidden and allow controlled access to it.
  • Data Validation: Setters allow you to validate data before updating properties.
  • Computed Properties: Getters can be used to create properties that are dynamically calculated from other values.