ES6: Use getters and setters to Control Access to an Object question

Tell us what’s happening:
Describe your issue in detail here.

Hello, I am new to JS (so maybe my question makes no sense).
Bellow is the correct answer for the challenge. However, my question is why when I typed at the end of the code: console.log(thermos.temperature) it gives 26 and does not use the equation in the setter? what’s the point of the equation in the setter if its not being used?

  **Your code so far**

// Only change code below this line
class Thermostat {
constructor(fahrenheit) {
  this.fahrenheit = fahrenheit;

get temperature() {
  return (5 / 9) * (this.fahrenheit - 32);

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
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 OPR/81.0.4196.61

Challenge: Use getters and setters to Control Access to an Object

Link to the challenge:

It is using the equation. It gets this.fahrenheit, subtracts 32, then multiplies by 5/9, and returns the result of that.

Note that when you use:

thermos.temperature = 26;

It calls the setter. It assumes that “26” is in C and converts it to F for storage. Then your getter converts it back.

It’s kind of an odd setup, but the point is to introduce you to getters and setters.

Does that makes sense?

1 Like

Oh, ok, I didn’t know that it will go back to the getter.
Yes, now it makes sense.
Thank you for your fast reply and explanation.

Yeah, it’s a little confusing, but when you reference thermos.temperature, if you are assigning a value, it calls the setter, if you are retrieving the value, it calls the getter. In some languages, you call the functions yourself. JS decide that you would just access it like it is a property and JS would figure out what to do, behind the scenes.

1 Like

Put the celsius formula in the constructor function as a value of this.fahrenheit, and use the parameter inside the formula, the setter and getter look cleaner with the job already done for them.
I think.

That probably would be a “smoother” implementation - to only make the conversion with the constructor and just store the value as celsius.

That makes more sense in terms of clean code. I suppose they wanted it this way to show that getters and setters can do more than just being a passthrough for class property.

I’ve always kind of hated this challenge - it seems unnecessarily confusing. But I also can’t think of a better one without losing some of the educative value or making things too complex.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.