Start learning free

LESSON 594 OF 635 · OBJECT-ORIENTED PROGRAMMING

Getters and Setters in JavaScript in JavaScript

Lesson

TL ; DR:

A getter reads a private field. A setter changes it, but only to a value the class allows.

In JavaScript, the keyword get in front of a method makes it the getter. The keyword set in front of a method with the same name makes it the setter. Other code still writes rex.age, as if it were a plain field.


class Dog {
    #age;

    constructor(age) {
        this.#age = age;
    }

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

    set age(value) {
        if (value >= 0) {
            this.#age = value;
        }
    }
}


Full lesson:

In the Access Modifiers lesson, getName() let other code read the private #name. Often other code must change a field too. A setter allows that, and it checks each new value first.

The getter

Write get age() inside the class. Now reading rex.age runs this method, with no parentheses. It returns the private this.#age.

The setter

Write set age(value) next to it. Now rex.age = 4 runs that method, with value set to 4.

The private field and the accessors need different names. Here the field is #age, and both accessors are age.

The rule

A dog's age can't be negative. So the setter changes this.#age only when value is 0 or more. After rex.age = -5, the age stays as it was.

Why not a plain field?

With a plain this.age, any code could set the age to -5. Nothing would check it. The accessors keep the rule inside the class. The code that uses rex.age stays the same.


Your task

The Dog class keeps its age in the private #age. Add a getter age that returns it. Add a setter age that ignores negative values.

The code below the class creates rex, then reads and sets rex.age.

Expected output:

Rex is 3
Rex is still 3
Rex is 4
STEP 1 OF 3
    Ctrl + Enter to check

    Getters And Setters in JavaScript

    Keep going with JavaScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free