Skip to main content

JavaScript Classes

JavaScript Class Getters and Setters

Written by Published

Class getters and setters let a method be used like a plain property.

The syntax is the same as in an object literal, but it matters more here.

Paired with a private field, a getter is how a class controls access to its data.

Example

Example

javascript

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  get area() {
    return this.width * this.height;
  }
}

console.log(new Rectangle(4, 5).area);

Note there are no brackets after area.

Getters and Setters in Classes

get before a method makes it run when the property is read.

set makes it run when the property is assigned.

They are ideal for exposing a private field safely.

Syntax

Syntax

javascript

get value() {
  return this.#value;
}

set value(v) {
  this.#value = v;
}

A setter takes exactly one parameter.

A Computed Property

It is recalculated every time it is read, so it never goes stale.

Example

Example

javascript

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  get area() {
    return this.width * this.height;
  }
}

const rect = new Rectangle(4, 5);
rect.width = 10;

console.log(rect.area);

The output is 50, updated automatically.

Exposing a Private Field

A getter with no setter makes a value read only from outside.

Example

Example

javascript

class Account {
  #balance = 100;

  get balance() {
    return this.#balance;
  }
}

const account = new Account();
account.balance = 999;

console.log(account.balance);

The assignment was ignored, because there is no setter.

Validating in a Setter

Bad values can be rejected before they are ever stored.

Example

Example

javascript

class Person {
  #age = 0;

  set age(value) {
    this.#age = value < 0 ? 0 : value;
  }

  get age() {
    return this.#age;
  }
}

const person = new Person();
person.age = -5;

console.log(person.age);

The output is 0, because the setter refused the negative value.

Splitting a Value

A setter can update several properties at once.

Example

Example

javascript

class Person {
  constructor(first, last) {
    this.first = first;
    this.last = last;
  }

  get fullName() {
    return this.first + " " + this.last;
  }

  set fullName(value) {
    const parts = value.split(" ");
    this.first = parts[0];
    this.last = parts[1];
  }
}

const person = new Person("Ada", "Lovelace");
person.fullName = "Grace Hopper";

console.log(person.first + " / " + person.fullName);

Reading and writing use the same natural name.

Getters Are Inherited

A child class gets its parent's accessors like any other method.

Example

Example

javascript

class Shape {
  get name() {
    return "shape";
  }
}

class Square extends Shape {}

console.log(new Square().name);

The child can override it by declaring its own getter.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Class Getters and Setters</title>
</head>
<body>

  <h1>Class Getters and Setters</h1>

  <p id="out"></p>

  <script>
    class Temperature {
      #celsius = 0;

      get celsius() {
        return this.#celsius;
      }

      set celsius(value) {
        this.#celsius = value;
      }

      get fahrenheit() {
        return this.#celsius * 9 / 5 + 32;
      }

      set fahrenheit(value) {
        this.#celsius = (value - 32) * 5 / 9;
      }
    }

    const temp = new Temperature();
    temp.fahrenheit = 212;

    document.getElementById("out").textContent =
      temp.fahrenheit + "F is " + temp.celsius + "C";
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try setting celsius:

Set temp.celsius = 37 and read the fahrenheit back.

Important Points

  • get runs when the property is read, with no brackets.
  • set runs when it is assigned.
  • A getter without a setter makes a property read only.
  • Setters are the right place for validation.
  • Accessors are inherited like ordinary methods.

Conclusion

Getters and setters keep a class's interface simple while it does real work behind it.

Together with private fields they give proper encapsulation.

A read-only property is often exactly what a class should expose.