The previous lesson in this module covered constructors and instance state, and this one builds on that by looking at getters, setters, and methods. JavaScript getters and setters are the feature that lets an object expose a property while still controlling what happens when that property is read or written. They are not renamed methods. A method is a function that you call with parentheses, while a getter is an accessor, which is a different kind of property altogether. Once you can see that difference in a property descriptor, you will know exactly when to reach for each of them. The next lesson in the module looks at how this is bound, which is the part that surprises everybody.
What is a getter and a setter, and when do you want one?
A getter is written with the get keyword in front of a name. A setter is written with set in front of the same name. The two halves are two views of one single property, so reading it runs the getter and writing it runs the setter.
class Temperature {
#celsius;
constructor(celsius) {
this.celsius = celsius;
}
get celsius() {
return this.#celsius;
}
set celsius(value) {
this.#celsius = value;
}
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
}
const morning = new Temperature(20);
console.log(morning.celsius);
console.log(morning.fahrenheit);
morning.celsius = 25;
console.log(morning.celsius);
console.log(morning.fahrenheit);
No parentheses appear at the place where the property is used. morning.celsius is a property read, and morning.celsius = 25 is a property write that happens to run some code. fahrenheit is a pure calculation with no setter at all, so it is read-only in practice, because there is no setter waiting to receive a value.
The decision rule is short. If the value is a property of the object, which means something with a name that people expect to see in an inspector, then use a property that is backed by a getter or a setter. If it is an action, or if it takes arguments, then use a method. temperature.fahrenheit reads like a property, which is why it is one. temperature.convertTo("kelvin") would be an action, so it belongs in a method.
Are getters just methods wearing a different hat?
No, and the difference is visible in the property descriptor. A method is a property whose value is a function. A getter is a property whose value is a pair of functions that are stored under the get and set keys.
class Temperature {
#celsius = 0;
get celsius() {
return this.#celsius;
}
set celsius(value) {
this.#celsius = value;
}
toString() {
return this.celsius + " C";
}
}
const descriptor = Object.getOwnPropertyDescriptor(Temperature.prototype, "celsius");
console.log(typeof descriptor.get);
console.log(typeof descriptor.set);
console.log("value" in descriptor);
console.log(descriptor.enumerable);
console.log(Object.getOwnPropertyNames(Temperature.prototype));
console.log(Object.keys(Temperature.prototype));
descriptor.get and descriptor.set are both functions, but the descriptor has no value key at all, and that is the giveaway that this is an accessor rather than a method. Accessors that are defined in a class body are non-enumerable, so descriptor.enumerable is false and Object.keys on the prototype returns an empty array. Object.getOwnPropertyNames still lists every member, including constructor, celsius, and toString.
Accessors live on the prototype, so every instance shares them in exactly the same way that instances share methods. What makes them different is what happens at the place where they are used. A method is a function that you invoke, while an accessor is a property that the engine intercepts for you.
How do you validate a value before it is stored?
Put the check inside the setter. Then every write goes through the same rule, whether the write comes from your own code, from a form handler, or from a test.
class Temperature {
#celsius = 0;
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (typeof value !== "number" || Number.isNaN(value)) {
throw new TypeError("celsius must be a number");
}
if (value < -273.15) {
throw new RangeError("below absolute zero");
}
this.#celsius = value;
}
}
const probe = new Temperature();
probe.celsius = 18;
console.log(probe.celsius);
try {
probe.celsius = "warm";
} catch (err) {
console.log(err.constructor.name + ": " + err.message);
}
try {
probe.celsius = -400;
} catch (err) {
console.log(err.constructor.name + ": " + err.message);
}
Assigning the string warm throws a TypeError with the message celsius must be a number. Assigning -400 throws a RangeError with the message below absolute zero. Using two different error types matters here, because it lets the caller tell "you sent the wrong kind of thing" apart from "you sent the right kind of thing with a value that is outside the allowed range".
Notice that the failed writes left the object untouched, because the check happens before the assignment, so probe.celsius is still 18. Throwing is only half of the story, though. Some callers would rather be handed a corrected value than an exception. If the setter quietly coerces or clamps the value, then the caller gets no signal that their input was wrong, and that is its own kind of bug.
What happens when you write to a property that only has a getter?
It depends on whether the writing code is strict. Class bodies are always strict, so code inside a class method gets an immediate TypeError. Loose code gets a silent no-op instead, which is much more dangerous because nothing tells you that the write failed.
"use strict";
class Reading {
#value = 0;
get value() {
return this.#value;
}
}
const reading = new Reading();
console.log(reading.value);
try {
reading.value = 42;
} catch (err) {
console.log(err.constructor.name + ": " + err.message);
}
console.log(reading.value);
The value starts at 0, the assignment throws a TypeError that reads Cannot set property value of #<Reading> which has only a getter, and the value is still 0 afterwards. If you remove the "use strict" line, then the same program prints 0 and then 0 again with no error at all, because the write is quietly discarded. That difference is worth knowing before you spend an afternoon wondering why a value never changes.
When should a method be static instead of an instance method?
A static method belongs to the class itself rather than to any one instance. It is the right home for a factory that builds instances, and for helpers that need no instance at all.
class Coordinate {
constructor(x, y) {
this.x = x;
this.y = y;
}
static origin() {
return new Coordinate(0, 0);
}
static fromDegrees(degrees, radius = 1) {
const radians = (degrees * Math.PI) / 180;
return new Coordinate(radius * Math.cos(radians), radius * Math.sin(radians));
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
toString() {
return "(" + this.x + ", " + this.y + ")";
}
}
const a = Coordinate.origin();
const b = Coordinate.fromDegrees(90, 10);
console.log(a.toString());
console.log(b.x.toFixed(4), b.y.toFixed(4));
console.log(a.distanceTo(b).toFixed(4));
console.log(typeof Coordinate.origin, typeof a.distanceTo);
Coordinate.origin() returns a point at (0, 0), and Coordinate.fromDegrees(90, 10) returns a point whose coordinates are approximately 0.0000 and 10.0000. The distance between them is 10.0000. The last line shows the split clearly, because Coordinate.origin is a static method and a.distanceTo is an instance method, and both of them are functions.
There are two practical notes here. First, static methods are inherited by subclasses, so a child class gets the factories of its parent for free unless it overrides them. Second, an instance method is not automatically tied to its instance, so pulling const d = a.distanceTo off the object and then calling d(b) loses the this that the method expects. That is the subject of the next lesson.
The short version of getters, setters, and methods
- A getter and a setter are one property with two halves, while a method is a property that holds a function.
- The place where they are used tells them apart:
obj.valuefor an accessor andobj.value()for a method. - Accessors live on the prototype, so they are shared, and they are non-enumerable when they are defined in a class body.
- Put validation inside the setter so that every write passes the same gate, and choose the error type to match the kind of mistake.
- A getter with no setter makes the property read-only, and strict code turns a bad write into a loud
TypeError. - Use static methods for factories and for helpers that need no instance.
Try it yourself: write a class Duration that stores a private #seconds field and that exposes it through a seconds getter and setter, plus a computed minutes getter that returns #seconds / 60. Make the setter reject negative numbers with a RangeError and reject non-numbers with a TypeError. Add a static factory static fromMinutes(mins) that builds a duration, and an instance method add(other) that returns a new duration with the summed seconds. Then run Object.getOwnPropertyDescriptor(Duration.prototype, "seconds") and confirm that it has get and set but no value key.