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
Getters and setters in JavaScript classes?
In this article we are going to discuss about the getters and setters in JavaScript classes with suitable examples in JavaScript.
In JavaScript, getters and setters are special methods that provide controlled access to object properties. They allow you to define custom behavior when getting or setting property values, ensuring data validation and encapsulation. Getters and setters use the get and set keywords respectively.
Let's explore how to implement getters and setters in JavaScript classes and objects with practical examples.
Syntax
The basic syntax for getters and setters:
class MyClass {
get propertyName() {
// return value
}
set propertyName(value) {
// set value with validation
}
}
Using Getters in Classes
Getters allow you to access properties like regular attributes while executing custom logic behind the scenes:
<html>
<head>
<title>Getters in JavaScript Classes</title>
</head>
<body>
<h3>Class Getters Example</h3>
<p id="result"></p>
<script>
class Student {
constructor(name, course, rollNo) {
this._name = name;
this._course = course;
this._rollNo = rollNo;
}
get details() {
return `${this._name} has registered for ${this._course} with roll no. ${this._rollNo}`;
}
get name() {
return this._name.toUpperCase();
}
}
const student1 = new Student('Ram', 'Computer Science', 22);
document.getElementById("result").innerHTML = student1.details + "<br>" + "Name: " + student1.name;
</script>
</body>
</html>
Using Setters in Classes
Setters allow you to validate and process data before assigning it to properties:
<html>
<head>
<title>Setters in JavaScript Classes</title>
</head>
<body>
<h3>Class Setters Example</h3>
<p id="result"></p>
<script>
class Employee {
constructor() {
this._name = '';
this._salary = 0;
}
set name(value) {
if (typeof value === 'string' && value.length > 0) {
this._name = value;
} else {
console.log('Invalid name');
}
}
set salary(value) {
if (value >= 0) {
this._salary = value;
} else {
console.log('Salary cannot be negative');
}
}
get name() {
return this._name;
}
get salary() {
return this._salary;
}
get details() {
return `Employee: ${this._name}, Salary: $${this._salary}`;
}
}
const emp = new Employee();
emp.name = 'John Doe';
emp.salary = 50000;
document.getElementById("result").innerHTML = emp.details;
</script>
</body>
</html>
Getters and Setters in Object Literals
You can also use getters and setters directly in object literals:
<html>
<head>
<title>Object Literal Getters and Setters</title>
</head>
<body>
<h3>Object Literal Example</h3>
<p id="result"></p>
<script>
const rectangle = {
_width: 0,
_height: 0,
set width(value) {
if (value > 0) {
this._width = value;
}
},
set height(value) {
if (value > 0) {
this._height = value;
}
},
get width() {
return this._width;
},
get height() {
return this._height;
},
get area() {
return this._width * this._height;
}
};
rectangle.width = 10;
rectangle.height = 5;
document.getElementById("result").innerHTML =
`Width: ${rectangle.width}<br>` +
`Height: ${rectangle.height}<br>` +
`Area: ${rectangle.area}`;
</script>
</body>
</html>
Static Getters and Setters
Classes can also have static getters and setters that belong to the class itself:
<html>
<head>
<title>Static Getters and Setters</title>
</head>
<body>
<h3>Static Getters Example</h3>
<p id="result"></p>
<script>
class MathUtils {
static get PI() {
return 3.14159265;
}
static get E() {
return 2.71828;
}
}
document.getElementById("result").innerHTML =
`PI: ${MathUtils.PI}<br>` +
`E: ${MathUtils.E}`;
</script>
</body>
</html>
Key Benefits
| Feature | Getter | Setter |
|---|---|---|
| Data Encapsulation | Controls how data is accessed | Controls how data is modified |
| Validation | Can compute values dynamically | Can validate before setting |
| Syntax | Accessed like a property | Set like a property |
Conclusion
Getters and setters provide elegant data encapsulation in JavaScript classes and objects. They enable property validation, computed properties, and cleaner APIs while maintaining simple property-like syntax for users of your classes.
