Object Get / Set
Getters and setters look like plain property access but run a function. They're handy for derived values and validation.
Defining
JS
const user = {
firstName: "Ada",
lastName: "Lovelace",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(value) {
[this.firstName, this.lastName] = value.split(" ");
},
};
user.fullName; // "Ada Lovelace" — getter called, no ()
user.fullName = "Grace Hopper"; // setter called with "Grace Hopper"
In classes
JS
class Temperature {
constructor(c) { this.celsius = c; }
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(f) {
this.celsius = (f - 32) * 5 / 9;
}
}
const t = new Temperature(20);
t.fahrenheit; // 68
t.fahrenheit = 100;
t.celsius; // ~37.78
Using Object.defineProperty
JS
Object.defineProperty(obj, "isAdmin", {
get() { return this.role === "admin"; },
enumerable: true,
});
When to use them
| Use accessors for… | Avoid them when… |
|---|---|
| Derived values that depend on other fields. | The operation is expensive — make it a method so the cost is visible. |
| Validating writes (clamp, normalise, reject). | You need the getter to be async — only methods can be async. |
| Backwards-compat shims for renamed fields. | Code that runs in hot loops — a plain property is cheaper. |
Tip: Don't make a getter that throws or has side effects. Readers expect property access to be cheap and pure.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Object Get / Set!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Define a computed property that returns "firstName lastName".
const user = { firstName: "Ada", lastName: "Lovelace",
fullName() { return this.firstName + " " + this.lastName; } };
Three letters.
Discussion
Loading…