get / set
Properties backed by functions: reading calls get, writing calls set.
Available since: ES5
Syntax
get name() { … } / set name(value) { … }Examples
A computed property:
class User {
constructor(first, last) {
this.first = first;
this.last = last;
}
get fullName() {
return `${this.first} ${this.last}`;
}
}
console.log(new User('Anna', 'Smith').fullName);Output:
Anna SmithValidating a value on write:
class Product {
#price = 0;
get price() {
return this.#price;
}
set price(value) {
if (value < 0) throw new RangeError('Price cannot be negative');
this.#price = value;
}
}
const tea = new Product();
tea.price = 5;
console.log(tea.price);
try {
tea.price = -1;
} catch (error) {
console.log(error.message);
}Output:
5
Price cannot be negativeNotes
A getter is read like a property, without parentheses: user.fullName, not user.fullName(). A getter without a setter makes the property read-only. It works in plain objects too: { get total() { … } }.
See also
- Private fields (#) — Fields and methods accessible only inside the class.
- class — Declares a class — a template for objects with shared methods.
- Object.defineProperty — Defines a property with exact settings: read-only, hidden, with a getter.
In the tutorial
- Getters and setters — Getters and setters in JavaScript classes: computed properties, validating values on write and read-only properties.