Some properties should be calculated rather than stored: a rectangle’s area, a person’s full name, a temperature in another unit. Others need checking before a new value is accepted: an exam mark must be between 0 and 100. Getters and setters let you write functions that look like ordinary properties from the outside, so you get the convenience of obj.area with the power of code.
In this lesson you will learn
- Writing
getandsetin object literals - Read-only computed properties
- Adding accessors with
Object.defineProperty - Getters and setters in classes with private fields
- Validating values on assignment
You should know objects, classes and the this keyword.
Getters and Setters in Objects
"use strict";
// A getter runs a function when a property is READ
const rectangle = {
width: 8,
height: 5,
get area() {
return this.width * this.height; // always up to date
},
};
console.log(rectangle.area); // no brackets: it looks like a property
rectangle.width = 10;
console.log(rectangle.area);
// A setter runs a function when a property is WRITTEN
const student = {
first: "Rina",
last: "Akter",
get fullName() {
return this.first + " " + this.last;
},
set fullName(value) {
const parts = value.trim().split(" ");
this.first = parts[0];
this.last = parts.slice(1).join(" ");
},
};
console.log(student.fullName);
student.fullName = "Tanvir Hasan Khan";
console.log(student.first, "|", student.last);
// A getter without a setter is read-only: writing throws in strict mode
try {
rectangle.area = 100;
} catch (err) {
console.log(err.name + ": area has no setter");
}
// Object.defineProperty adds an accessor to an existing object
const temperature = { celsius: 30 };
Object.defineProperty(temperature, "fahrenheit", {
get() { return this.celsius * 9 / 5 + 32; },
set(f) { this.celsius = (f - 32) * 5 / 9; },
enumerable: true,
});
console.log(temperature.fahrenheit);
temperature.fahrenheit = 212;
console.log(temperature.celsius);
console.log(Object.keys(temperature));
Output
40
50
Rina Akter
Tanvir | Hasan Khan
TypeError: area has no setter
86
100
[ 'celsius', 'fahrenheit' ]
get area() { … }defines a getter. Readingrectangle.area, with no brackets, runs the function. Because it is recalculated on every read, it is always up to date afterwidthchanges.set fullName(value) { … }defines a setter. Assigningstudent.fullName = "…"runs it with the new value, and here it splits the name into its parts.- A getter and setter can share a name: reading uses one, writing uses the other.
- A property with a getter but no setter is read-only. In strict mode, assigning to it throws a
TypeError; in sloppy mode it fails silently. Object.definePropertyadds an accessor to an existing object. Accessors added this way are hidden fromObject.keysunless you setenumerable: true.
Getters and Setters in Classes
"use strict";
// Getters and setters in a class, with a private field holding the real value
class BankAccount {
#balance = 0; // private: cannot be reached from outside
constructor(owner) {
this.owner = owner;
}
get balance() { // read-only from outside
return this.#balance;
}
get formatted() {
return this.#balance.toLocaleString("en-US") + " taka";
}
deposit(amount) {
if (!(amount > 0)) throw new RangeError("Deposit must be positive");
this.#balance += amount;
}
}
class Exam {
#mark = 0;
get mark() { return this.#mark; }
set mark(value) { // validation happens on every assignment
if (!Number.isInteger(value) || value < 0 || value > 100) {
throw new RangeError("Mark must be a whole number from 0 to 100, got " + value);
}
this.#mark = value;
}
get grade() { // computed from the mark
const m = this.#mark;
return m >= 80 ? "A+" : m >= 70 ? "A" : m >= 60 ? "A-" : m >= 50 ? "B" : m >= 40 ? "C" : m >= 33 ? "D" : "F";
}
}
const acc = new BankAccount("Rina");
acc.deposit(15000);
acc.deposit(2500);
console.log(acc.owner, acc.balance, acc.formatted);
try { acc.balance = 1000000; } catch (err) { console.log(err.name + ": balance is read-only"); }
const exam = new Exam();
exam.mark = 72;
console.log(exam.mark, exam.grade);
for (const bad of [105, 7.5]) {
try { exam.mark = bad; } catch (err) { console.log(err.message); }
}
console.log("Mark is still", exam.mark);
Output
Rina 17500 17,500 taka
TypeError: balance is read-only
72 A
Mark must be a whole number from 0 to 100, got 105
Mark must be a whole number from 0 to 100, got 7.5
Mark is still 72
- The real value lives in a private field,
#balance, which code outside the class cannot touch. The public getterbalancelets others read it but not change it. - Money can only enter through
deposit(), which checks the amount. Writing!(amount > 0)also rejectsNaN, which a plainamount <= 0check would let through. - The
Examclass validates every assignment in its setter. Invalid marks throw aRangeError, and the old value is kept. gradeis computed from the mark using the SSC grading scale, so it can never disagree with the mark.- Getters and setters are defined on the class’s prototype, so all objects share one copy of the functions.
When to Use Them
| Use | Example |
|---|---|
| Derived values | area, fullName, grade, total |
| Validation | Rejecting a negative price or an impossible mark |
| Read-only access | Exposing a private balance without allowing changes |
| Unit conversion | Celsius and Fahrenheit views of one value |
| Avoid for | Slow work or work with side effects, such as network requests: use a normal method so callers can see that something happens |
Common Mistakes
- Infinite recursion:
set name(v) { this.name = v; }calls itself forever. Store the value in a different property, such as#name. - Calling a getter with brackets:
rectangle.area()throws, becauseareareturns a number, not a function. - Expensive getters that recalculate a lot of data every time they are read in a loop.
- Expecting
JSON.stringifyto include class getters. It includes only own enumerable data properties, so add atoJSON()method if you need them.
Practice Exercises
Exercise 1. Give a cart object with an items array of { price, qty } a total getter.
Show answer
const cart = {
items: [{ price: 120, qty: 2 }, { price: 50, qty: 3 }],
get total() {
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
},
};
console.log(cart.total); // 390
Exercise 2. Write a class Username whose value setter trims spaces and throws if the result is shorter than 3 characters.
Show answer
class Username {
#value = "";
get value() { return this.#value; }
set value(v) {
const t = String(v).trim();
if (t.length < 3) throw new RangeError("Username needs at least 3 characters");
this.#value = t;
}
}
Frequently Asked Questions
Should I write getName() or a getter called name?
Use a getter for cheap values that feel like properties. Use a method when the work is expensive, needs arguments, or does something noticeable, such as fetching data.
Can getters be static?
Yes. A static getter, such as static get count(), belongs to the class itself rather than to each object, and is read as ClassName.count.
Summary
- Getters run when a property is read; setters run when it is assigned.
- Use getters for derived values and setters for validation.
- Pair them with private fields to control access to data.
- Never assign to the same property inside its own setter.
Next: Drag and Drop.
