DEV Community

Shifa
Shifa

Posted on

Getters and Setters in JavaScript

In JavaScript, getters and setters are special methods that allow you to control access to the properties of an object. They are primarily used to define object properties dynamically, encapsulate logic, and ensure data integrity. By using getters and setters, developers can control how properties are read and written without directly exposing the underlying data structure.

What are Getters and Setters?

  • Getter: A method that gets the value of a specific property.
  • Setter: A method that sets or updates the value of a specific property.

They are defined using the get and set keywords inside an object or class.

Why Use Getters and Setters?

  • Encapsulation: Hide the internal representation of data.
  • Validation: Apply logic before assigning or retrieving values.
  • Computed Properties: Dynamically calculate values based on other properties.
  • Consistency: Uniform access to data, whether stored or computed.

Syntax

In Object Literals

const person = {
  firstName: "John",
  lastName: "Doe",

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },

  set fullName(name) {
    const parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

console.log(person.fullName); // John Doe
person.fullName = "Jane Smith";
console.log(person.firstName); // Jane
console.log(person.lastName);  // Smith
Enter fullscreen mode Exit fullscreen mode

In ES6 Classes

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

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

  set dimensions({ width, height }) {
    if (width > 0 && height > 0) {
      this._width = width;
      this._height = height;
    } else {
      throw new Error("Dimensions must be positive numbers.");
    }
  }
}

const rect = new Rectangle(10, 20);
console.log(rect.area); // 200
rect.dimensions = { width: 15, height: 25 };
console.log(rect.area); // 375
Enter fullscreen mode Exit fullscreen mode

Key Considerations

  • Prefixing internal properties with an underscore (e.g., _width) is a common convention to indicate that they are meant to be private.
  • Avoid complex logic inside getters and setters to maintain readability and performance.
  • Use getters and setters when there’s a clear benefit, such as validation, transformation, or abstraction.

Use Cases

  • Creating derived properties (e.g., fullName from firstName and lastName).
  • Validating input before updating a value.
  • Triggering side effects (with caution) when a property changes.
  • Protecting private data from being directly manipulated.

Conclusion

Getters and setters in JavaScript are powerful tools for object-oriented programming and data encapsulation. By defining custom behavior when properties are accessed or modified, you can write more robust, maintainable, and secure code. However, they should be used thoughtfully to avoid unnecessary complexity.


Top comments (0)