Getters and Setters explanation

I’m having such a hard time with the getters and setters challenge. I finished the basic Javascript challenges, all the other ES6 challenges, and the Regex challenges as well, but I can’t figure this one out.

Can anyone explain what the code from the solution is doing step-by-step? Here’s the official solution:


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;
  }
}

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

Link to the challenge:

  • Next time you want to showcase a code, use the ` backtick so it is easier for everyone to read.
    See this post to find the backtick on your keyboard.
    The “preformatted text” tool in the editor (</>) will also add backticks around text.

Noted, thanks for the tip!

What part is confusing? The general idea is that you are not allowing direct access to the variables inside the object. Instead you are providing some input preprocessing, output conversion, etc. Often you use setters for input validation.