All topics
Objectsintermediate

Getters and Setters

Defining object properties backed by functions that run on access or assignment, letting you compute values or add validation transparently.

Getters and setters let you define an object property that, from the outside, looks and behaves exactly like a plain data property — accessed and assigned with ordinary dot notation — but is actually backed by functions that run automatically on read or write. This is a useful but sometimes overlooked feature, and interviewers ask about it to check whether you know JavaScript objects support more than plain key-value pairs.

A getter/setter pair is like a smart thermostat display: you read a single number (the property) that's actually computed live from several sensors (a getter), and when you dial in a new target temperature (a setter), the internal system runs it through validation and translates it into the actual settings, all while you just interact with one simple dial.

Key Concepts

1
Inside an object literal or a class body, a getter is defined with the get keyword before a method name (get fullName() { return \${this.first} ${this.last}\; }), and accessing obj.fullName calls that function and returns its result, computed fresh every time rather than stored. A setter uses the set keyword (set fullName(value) { [this.first, this.last] = value.split(' '); }) and runs automatically whenever obj.fullName = 'New Name' is assigned, letting you intercept the assignment to validate, transform, or split the incoming value before storing it in real backing properties.
getget fullName() { return \; }obj.fullNameset
2
A very common pattern pairs a getter/setter with a private backing field (often prefixed with an underscore by convention, or using true private class fields with #) so that external code interacts only through the computed/validated property, never directly with the raw underlying value — this gives you a clean way to add validation logic (like rejecting a negative age) without changing how consumers of the object read or write the property.
#
3
Getters and setters can also be defined on the fly with Object.defineProperty(), which is useful for adding computed behavior to an existing object outside of a class or object literal declaration. It's worth noting that a property can have a getter without a setter (making it effectively read-only from the outside, since assignment silently fails or throws in strict mode) or vice versa, and defining only one while consumers attempt the other is a common source of confusing bugs.
Object.defineProperty()