DEV Community

Web Easly
Web Easly

Posted on

JavaScript Object Accessors

JavaScript, as a versatile language, empowers developers with various techniques to manipulate object properties. Object accessors, particularly getters and setters, offer a dynamic way to control how these properties are accessed and modified.

Getters: Retrieving Values Dynamically

Getters are functions that enable controlled access to an object's properties. They intercept property access and compute the value on the fly. Consider this example:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

console.log(person.fullName); // Output: John Doe
Enter fullscreen mode Exit fullscreen mode

In this snippet, the fullName getter amalgamates firstName and lastName when accessed, providing a cohesive representation of the person's full name.

Setters: Modifying Properties with Control

Setters, on the other hand, allow controlled assignment to properties. They provide a way to execute custom logic before setting a value. Here's an illustration:

const temperature = {
  _celsius: 0,
  get celsius() {
    return this._celsius;
  },
  set celsius(value) {
    if (value < -273.15) {
      throw new Error('Temperature cannot be below -273.15°C (Absolute Zero)');
    }
    this._celsius = value;
  },
};

temperature.celsius = 25; // Setting the temperature
console.log(temperature.celsius); // Output: 25

temperature.celsius = -300; // Attempting to set an invalid temperature
// Throws an error: Temperature cannot be below -273.15°C (Absolute Zero)
Enter fullscreen mode Exit fullscreen mode

This example uses a celsius setter to validate and restrict the assigned temperature to physically feasible values.

Practical Applications

Data Validation and Transformation

Object accessors are invaluable for data validation. They enable developers to enforce constraints on property values, ensuring data integrity.

const user = {
  _password: '',
  get password() {
    return this._password;
  },
  set password(newPassword) {
    if (newPassword.length < 6) {
      throw new Error('Password must be at least 6 characters long');
    }
    this._password = newPassword;
  },
};

user.password = 'abc123'; // Setting a valid password
console.log(user.password); // Output: abc123

user.password = 'pass'; // Attempting to set an invalid password
// Throws an error: Password must be at least 6 characters long
Enter fullscreen mode Exit fullscreen mode
Calculated Properties

Getters are useful for creating calculated properties that depend on other object properties.

const rectangle = {
  width: 5,
  height: 10,
  get area() {
    return this.width * this.height;
  },
};

console.log(rectangle.area); // Output: 50
Enter fullscreen mode Exit fullscreen mode

Compatibility and Browser Support

Object accessors, including getters and setters, are supported in modern JavaScript environments. However, for broader compatibility, it's essential to verify the compatibility with targeted browsers or runtime environments, as older browsers might lack support for these features.

Conclusion

JavaScript object accessors, through getters and setters, offer a flexible means to control access to object properties. They empower developers to enforce logic, perform validation, and create computed or derived properties, enhancing code readability, maintainability, and data integrity in JavaScript applications.

Top comments (0)