Why is class defined under function ? Ch. "ES6: Use getters and setters to Control Access to an Object"

Please refer to chapter " ES6: Use getters and setters to Control Access to an Object"

  1. Why is class defined under a function ?

  2. I didn’t understand return Thermostat; statement after class definition ?

  3. If I comment out code which is related to function then also it works fine, then which case/s I should definite class within a function. This concept is super confusing for Java engineer like me :thinking:

function makeClass() {
  "use strict";
  /* Alter code below this line */
  class Thermostat{
      this._tempInFahrenheit = tempInFahrenheit;

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

    set temperature(tempInCelcius){
      this._tempInFahrenheit = tempInCelcius * 9.0 /5 +32;

  /* Alter code above this line */
  return Thermostat;
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C

That’s a good question. I don’t see any reason it should be. Maybe it has something to do with how it’s tested?

1 Like

The only good reason I can think of, is that “boxes” the definition inside a function, so it’s not defined in the global scope.

For example with a class definition the JS engine will throw error if you try to duplicate classes:

class C {
  constructor(id) {
    this.id = id

class C {
  constructor(x) {
    this.iAmDifferent = x;

// SyntaxError: Duplicate declaration "C" at [...]

However having it in a function will let you do that.
Why you want to such thing is a totally different question :wink:

Perhaps it’s related to some testing made under the hood as @br3ntor said.

1 Like

It’s just for the testing, it creates a local scope where to activate strict mode
It is probably deprecated now, some challenges have already been changed


Thanks @br3ntor @Marmiz @ilenia for clarifications.