JS Accessors

HTML
CSS
C#
SQL

Accessors (Getters and Setters)

In JavaScript, object accessors refer to the use of getters and setters to control access to an object’s properties. They allow you to define computed properties, providing a way to get and set values in a controlled manner.

Getter (The get Keyword):

A getter is a method that gets the value of a specific property. It is defined using the get keyword within an object.

Example:

In this example, the lang property acts as a getter, allowing you to retrieve the value of the language property using person.lang.

Setter (The set Keyword):

A setter is a method that sets the value of a specific property. It is defined using the set keyword within an object.

Example:

const person = {
  firstName: “John”,
  lastName: “Doe”,
  language: “”,
  set lang(lang) {
    this.language = lang;
  }
};

// Setting the value using the setter
person.lang = “en”;

// Displaying the set value
console.log(person.language); // Output: en

In this example, the lang property acts as a setter, allowing you to set the value of the language property using person.lang = “en”.

Combining Getter and Setter:

You can combine both getter and setter in the same property, providing full control over the property’s access.

Example

const temperature = {
  _celsius: 25,
  get fahrenheit() {
    return this._celsius * 9/5 + 32;
  },
  set fahrenheit(value) {
    this._celsius = (value – 32) * 5/9;
  }
};

// Getting and setting the temperature
console.log(temperature.fahrenheit); // Output: 77
temperature.fahrenheit = 32; // Set temperature in Fahrenheit
console.log(temperature._celsius); // Output: 0

In this example, the Fahrenheit property acts as both a getter and a setter, allowing you to get and set the temperature in both Fahrenheit and Celsius.

Course Video