DEV Community

Simon Mei
Simon Mei

Posted on

Boiled down: Getters/setters in JavaScript

Security and flexibility with getters and setters

In JavaScript, there are two kinds of object properties:

  1. Data properties:
let myObj = {name: "Joseph", surname: "Joestar"}
// name and surname are data properties

myObj.name // Joseph
Enter fullscreen mode Exit fullscreen mode
  1. Accessor properties
let myObj = {
  get name() {
    return this._name;
  },
  set name(value) {
    this._name = value;
  },
  get surname() {
    return this._surname;
  },
  set surname(value) {
    this._surname = value;
  },
  get fullName() {
    return `${this._name} ${this._surname}`
  }
}
// properties starting with an underscore are internal
// and should not be touched outside the object

// get name and set name are accessor properties
myObj.name = "Jolene"
myObj.name // Jolene
Enter fullscreen mode Exit fullscreen mode

You can see how data properties allow us to directly access an object's properties, whereas accessor properties provide us getters and setters to retrieve and manipulate an object's properties.

We can even keep the actual value under a different variable name. But why should we use accessor properties? They allow us more control over operations with our objects and safeguard data that we don't want to be directly accessed or manipulated.

Within our setter, we can manipulate the data before storing it in our object's property such as validation.

Compatability using getters and settters

If we introduce new properties in the future for an object that may affect other properties, we can modify the accessor properties to make it compatible with our current needs.

Top comments (0)