By the end, you can define JavaScript getters and setters so an object exposes computed properties that run functions when read or assigned.
What it is
A getter is a function that runs when you read a property. A setter is a function that runs when you assign to a property. Together they create an accessor property: it looks like ordinary data from the outside, but the value is computed, validated, or stored internally when accessed.
The mental model is “property syntax, method behavior.” Related terms include accessor property, computed value, data property, and Object.defineProperty.
Why it matters
- Validate input before storing it, such as rejecting negative ages.
- Derive values from other fields, such as building
fullNamefromfirstandlast. - Hide internal state while keeping a clean public API.
- Trigger side effects, such as logging, caching, or recalculating totals.
- Make objects easier to use because callers do not need to remember method names.
Syntax or steps
- Inside an object literal, write
get propertyName()for reading. - Return the value you want the property to expose.
- Write
set propertyName(value)for assignment. - Use
thisto read or update related properties. - Access the property normally:
obj.propcalls the getter,obj.prop = xcalls the setter.
const obj = {
get propName() {
return "computed value";
},
set propName(value) {
// store or validate value
}
};
Example
const person = {
first: "Ada",
last: "Lovelace",
get fullName() {
return `${this.first} ${this.last}`;
},
set fullName(name) {
const [first, last] = name.split(" ");
this.first = first;
this.last = last;
}
};
console.log(person.fullName);
person.fullName = "Grace Hopper";
console.log(person.first, person.last);
fullNameis not stored as a normal property; it is computed fromfirstandlast.- Reading
person.fullNamecalls the getter and returns"Ada Lovelace". - Assigning
person.fullName = "Grace Hopper"calls the setter. - The setter splits the string and updates the underlying fields.
- The final log prints
Grace Hopper.
Common mistakes
- Forgetting
returnin a getter. The property becomesundefined. - Naming the getter or setter the same as the backing field, causing recursion. Use a different internal name, such as
_first, or a private field in a class. - Writing a setter with no parameter. The setter needs the assigned value, for example
set age(value). - Detaching the method from the object. If you copy the getter to another variable,
thismay no longer point to the original object.
When to use it
Use getters and setters when the value feels like a property. Use ordinary methods when the operation feels like an action or needs multiple arguments.
| Need | Use | Why |
|---|---|---|
| Read a derived value | getter | Callers can use obj.fullName instead of obj.getFullName(). |
| Validate or transform assignment | setter | Callers can use obj.age = 30 while the object controls storage. |
| Perform an action | method | Names like save() or reset() are clearer than property syntax. |
| Define accessors dynamically | Object.defineProperty | Useful when property names are generated at runtime. |
Practice
Guided exercise: create an object named temp with a celsius property and a getter named fahrenheit that returns celsius * 9 / 5 + 32.
const temp = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
};
console.log(temp.fahrenheit);
Expected output: 68.
Challenge: add a setter named fahrenheit that converts a Fahrenheit value back to Celsius and stores it in celsius. Hint: use (value - 32) * 5 / 9.
Quick check
Question: What happens if a getter and setter use the same property name as the field they try to store?
Answer: They can call themselves recursively, often causing a stack overflow. Use a different backing field name or a private field.
Summary
Getters and setters let JavaScript objects expose computed or controlled properties using normal property syntax. They are best for derived values and validation, while methods remain better for actions and multi-argument operations.