Getter and setter - passed but don't understand


So I just finished the Using Getters and Setters thermostat activity in ES6.

I’m having trouble understanding what is happening with the setter code.

// Only change code below this line
class Thermostat {
  constructor(fahrenheit) {
    this.fahrenheit = fahrenheit;
  // getter
  get temperature () {
    return (5 / 9) * (this.fahrenheit - 32);
  // setter
  set temperature (celsius) {
    this.fahrenheit = (celsius * 9.0) / 5 + 32;

// Only change code above this line

const thermos = new Thermostat(76); // Setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in Celsius
thermos.temperature = 26;
temp = thermos.temperature; // 26 in Celsius

I understand how const thermos = new Themostat(76); is being converted using the getter

What I am not clear about is whether it is passing a celsius temperature into the setter. It doesn’t appear to be, but I’m not sure. If it is passing a celsius temperature into the setter then how is it working?

Thank you for your help :slight_smile:

That line doesn’t deal with the getter or the setter; that line invokes the constructor, which uses Fahrenheit and involves no conversion.

Internally, the objects stores temperature in Fahrenheit. However, the getter and setter provide access to the temperature in Celsius.

This line uses the getter to retrieve the stored Fahrenheit temperature converted to Celsius.

This line uses the setter to update the stored Fahrenheit temperature after converting the provided Celsius value.

1 Like

Okay so thermos.temperature = 26; passing the 26 into the setter thus updating fehrenheit to 78?

I’m just trying to make sure I understand it correctly.

Exactly. The getter/setter are handling the conversion in this case.

In general, getter/setters handle conversion, error checking, validation, etc. They provide abstraction, so the internal details of the object’s code can be changed but the person using the getter/setter will get the exact same result.

1 Like

Okay, that makes sense. I think I was getting hung up on lack of parentheses. I assumed that to pass a value/string into the setter I would have to use parentheses to connect it with the word Celsius. Is there a reason that parentheses are not required for this?

Thank you for the explanations :slight_smile:

I am not the right person to ask why parenthesis are not needed here. I know they are not needed, but I don’t have a super satisfying answer as to why. Hopefully someone will chime in with their deeper knowledge on the design of JavaScript.

1 Like