Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between getter and setter in JavaScript?
In JavaScript, getters and setters are special methods that allow you to define how properties are accessed and modified in objects. They provide a way to control property access while maintaining a clean interface.
Getter
A getter is a method that gets executed when a property is accessed. It uses the get keyword and allows you to define custom logic for retrieving a property value. The getter appears as a regular property but internally calls a function.
Setter
A setter is a method that gets executed when a property is assigned a value. It uses the set keyword and receives the assigned value as a parameter. Setters allow you to validate, transform, or perform actions when a property is modified.
Basic Syntax
const obj = {
get propertyName() {
// Return property value
},
set propertyName(value) {
// Set property value
}
};
Example: Department Object
<html>
<body>
<script>
var department = {
deptName: "Finance",
deptZone: "South",
deptID: 105,
get details() {
return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
},
set details(info) {
var res = info.toString().split(' ');
this.deptName = res[0] || '';
this.deptZone = res[1] || '';
this.deptID = res[2] || '';
}
}
// Using setter
department.details = 'Marketing North 001';
// Using getter
document.write(department.details);
</script>
</body>
</html>
Node.js Example
class Temperature {
constructor() {
this._celsius = 0;
}
get fahrenheit() {
return (this._celsius * 9/5) + 32;
}
set fahrenheit(temp) {
this._celsius = (temp - 32) * 5/9;
}
get celsius() {
return this._celsius;
}
}
const temp = new Temperature();
temp.fahrenheit = 100;
console.log(`${temp.celsius}°C = ${temp.fahrenheit}°F`);
37.77777777777778°C = 100°F
Key Differences
| Aspect | Getter | Setter |
|---|---|---|
| Keyword | get |
set |
| Purpose | Retrieve property value | Set property value |
| Parameters | None | One (the new value) |
| Return Value | Required | Not needed |
Benefits
Getters and setters provide encapsulation, data validation, and computed properties while maintaining a simple property access syntax. They're essential for creating robust object-oriented JavaScript applications.
Conclusion
Getters retrieve property values with custom logic, while setters handle property assignment with validation or transformation. Both use special keywords and provide controlled access to object properties.
