Getters, setters & #private fields
Guarded properties
Lesson 10 of 20 · 11 min · Module 3: Classes and objects
Some properties must always stay valid, and some should be calculated instead of stored. Getters and setters run code behind normal property syntax, and private fields keep the real data out of reach.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Compute properties with getters
- Validate assignments with setters
- Hide data with #private fields
The idea
get name() runs when the property is read; set name(value) runs when it is assigned. A field whose name starts with # is private: only code inside the class can read or change it.
class Person {
#name;
constructor(name) { this.name = name; }
get name() { return this.#name; }
set name(value) {
if (!value.trim()) throw new Error("name required");
this.#name = value.trim();
}
}
console.log(new Person(" Ana ").name);
01Same syntax, more control
Callers write t.fahrenheit = 212 as with any property. Behind it, the setter converts and validates, so outside code never needs to know the details.
02Truly private
this.#celsius exists only inside the class body. Code outside cannot read it, change it, or even see it in Object.keys or JSON.stringify.
class Box {
#secret = 42;
reveal() { return this.#secret; }
}
const b = new Box();
console.log(Object.keys(b).length, b.reveal());0 4203One source of truth
Only Celsius is stored. Fahrenheit is always derived from it, so the two values can never disagree.
Your turn
Temperature that stores degrees Celsius in a private field. celsius is a getter/setter that throws a RangeError below -273.15 (also in the constructor). fahrenheit is a getter/setter that converts with c * 9 / 5 + 32. Instances must have no visible own properties.What the checks look for
- Stores celsius and converts to fahrenheit
- Setting fahrenheit updates celsius
- Rejects temperatures below absolute zero
- Keeps its data private
Take this with you
Getters compute, setters guard, private fields protect.
Go a little further
Add a static method Temperature.fromFahrenheit(f) that creates an instance from a Fahrenheit value.