Computed properties
Expose a computed value from existing object state.
JS Puzzles · Const
Getters and setters create accessor properties that look like ordinary fields to callers. Reads invoke the getter, while assignments invoke the setter.
An accessor property uses a getter for reads and a setter for assignments. The getter is declared with get and takes no argument; the setter is declared with set and receives the value being assigned, while both expose property-like syntax to callers.
const object = {
get property() { /* return value */ },
set property(value) { /* handle assignment */ }
};| Name | Type | Description |
|---|---|---|
value | any | The getter has no parameters; the setter receives the value assigned to the property. |
A getter returns the value produced on property read; a setter does not provide a property-read result.
const user = {
firstName: "Ada",
lastName: "Lovelace",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(value) {
[this.firstName, this.lastName] = value.split(" ");
}
};
console.log(user.fullName);
user.fullName = "Grace Hopper";
console.log(user.firstName);Reading fullName invokes the getter; assigning to it invokes the setter.
Expose a computed value from existing object state.
Validate, normalize, or transform values before storing them.
Keep callers on a stable property-like API while changing internal storage.
A getter is a function associated with a property and runs when that property is read. A setter is associated with a property and runs when a value is assigned to it.
Follow-up: How are accessor functions represented in a property descriptor? A descriptor can contain get and set functions; get has no arguments, while set receives one argument.
In an object literal, prefix the property definition with get or set. The getter uses property-read syntax, such as object.name, and the setter uses assignment syntax, such as object.name = value.
Follow-up: Can accessors be added after object creation? Yes: define them later with Object.defineProperties(), or use a property-definition API for an individual property.
Accessor properties let callers use normal property syntax while the implementation controls reads and writes. This makes them useful as wrappers around stored values, for example to validate or transform assigned data.
Follow-up: What must a setter do with its input? It can validate or transform the single assigned value before updating separate backing state.
Object.definePropertiesObject.definePropertyproperty descriptorsobject literals