How to Use Getter and Setter in JavaScript: Simple Guide
In JavaScript, use
get to define a getter method that returns a property value, and set to define a setter method that updates a property value. These methods allow controlled access to object properties while hiding internal details.Syntax
A getter is defined with the get keyword followed by a method that returns a value. A setter uses the set keyword followed by a method that takes one parameter to update a value.
Both are defined inside an object or a class and accessed like normal properties.
javascript
const obj = { get propName() { // return a value }, set propName(value) { // update something with value } };
Example
This example shows an object with a private property _name and getter/setter to access and modify it safely.
javascript
const person = { _name: 'Alice', get name() { return this._name; }, set name(newName) { if (typeof newName === 'string' && newName.length > 0) { this._name = newName; } else { console.log('Invalid name'); } } }; console.log(person.name); // Alice person.name = 'Bob'; console.log(person.name); // Bob person.name = ''; // Invalid name console.log(person.name); // Bob
Output
Alice
Bob
Invalid name
Bob
Common Pitfalls
- Forgetting to use
thisinside getter/setter to access the actual property. - Creating infinite loops by setting the property inside its own setter without a separate backing variable.
- Setter not validating input, allowing invalid data.
javascript
const obj = { value: 0, get val() { return this.value; }, set val(newVal) { // Wrong: setting val inside setter causes infinite loop // this.val = newVal; // Right: set backing property this.value = newVal; } };
Quick Reference
Use getters and setters to control how properties are accessed and changed. Getters return values, setters receive new values. Always use a separate internal property to avoid recursion.
| Concept | Description | Example |
|---|---|---|
| Getter | Returns a property value | get prop() { return this._prop; } |
| Setter | Sets a property value | set prop(value) { this._prop = value; } |
| Access | Use like a property, not a method | obj.prop = 5; console.log(obj.prop); |
| Backing Property | Internal variable to store value | this._prop |
Key Takeaways
Use
get and set keywords to define property accessors in objects or classes.Always use a separate internal property to store data to avoid infinite loops in setters.
Getters allow you to run code when a property is read; setters run code when a property is assigned.
Validate input inside setters to keep data consistent and safe.
Access getters and setters like normal properties, without parentheses.