Start learning free

LESSON 32 OF 69 · OBJECT-ORIENTED PROGRAMMING

Getters and Setters in JavaScript: get, set and #

Lesson Read the full explanation

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

    JAVASCRIPT · OBJECT-ORIENTED PROGRAMMING

    Getters And Setters in JavaScript, explained

    What getters and setters are

    A getter lets other code read a private field. A setter lets other code change it, but only to values the class accepts. In JavaScript they are written with the keywords get and set in front of a method name.

    class Dog {
        #age;
    
        constructor(age) {
            this.#age = age;
        }
    
        get age() {
            return this.#age;
        }
    
        set age(value) {
            if (value >= 0) {
                this.#age = value;
            }
        }
    }
    

    The private field is #age. The getter and the setter are both named age, without the #. Code outside the class never sees the field. It sees what looks like a plain property called age.

    How they are used

    A getter runs when the property is read, and a setter runs when it is assigned. There are no parentheses in either case:

    let rex = new Dog(3);
    console.log("Rex is " + rex.age);
    rex.age = -5;
    console.log("Rex is still " + rex.age);
    rex.age = 4;
    console.log("Rex is " + rex.age);
    
    Rex is 3
    Rex is still 3
    Rex is 4
    

    rex.age on the right runs get age(). The line rex.age = 4 runs set age(value) with value equal to 4. The assignment rex.age = -5 also runs the setter, but the if fails, so #age keeps its old value and the program prints "Rex is still 3".

    Why not a plain field?

    With a plain this.age, any code could assign -5 and nothing would check it. With a setter, the rule "an age is never negative" lives inside the class, in one place. The code that uses rex.age looks the same either way, so a class can start with a plain property and later add a rule without changing its users.

    The exercise, step by step

    1. Write the getter. Below the constructor add get age() with its braces. It returns this.#age.
    2. Open the setter. Below the getter add set age(value), again with braces. A setter takes exactly one parameter, the assigned value.
    3. Add the rule. Inside the setter, an if on value >= 0 stores value in this.#age. For a negative value nothing happens.

    The solution, with the code that prints the expected output:

    class Dog {
        #age;
    
        constructor(age) {
            this.#age = age;
        }
    
        get age() {
            return this.#age;
        }
    
        set age(value) {
            if (value >= 0) {
                this.#age = value;
            }
        }
    }
    
    let rex = new Dog(3);
    console.log("Rex is " + rex.age);
    rex.age = -5;
    console.log("Rex is still " + rex.age);
    rex.age = 4;
    console.log("Rex is " + rex.age);
    

    Traps

    • The accessor and the field need different names. The getter is age and the field is #age. If the getter reads this.age it calls itself, and the program stops with RangeError: Maximum call stack size exceeded.
    • A getter without a setter is read-only. With only get age(), the assignment c.age = 9 does nothing in ordinary top-level code, and c.age still returns the old value. Inside a class body or a strict-mode function it throws TypeError: Cannot set property age of #<Cat> which has only a getter.
    • The setter's rejection is silent. Assigning -5 gives no error. If callers should be told, throw an error in the setter instead of skipping the assignment.
    • Accessors are not properties of the object itself. They live on the class, so Object.keys(rex) and JSON.stringify(rex) give an empty list and {}, and the private field does not show up either.

    Key takeaways

    • get name() runs when obj.name is read. set name(value) runs when obj.name = value is assigned.
    • Keep the data in a # field with a different name from the accessor.
    • Put the validation in the setter, so the rule exists in one place.
    • Leave out the setter to make a value readable but not changeable.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free