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
Selected Reading
Using the get in JavaScript to make getter function
The get keyword in JavaScript creates a getter method that allows you to access object properties like regular properties while executing custom logic behind the scenes.
Syntax
const obj = {
get propertyName() {
// Custom logic
return value;
}
};
Basic Example
const studentDetails = {
_name: "David Miller",
get studentName() {
console.log('I am calling the getter method...');
return this._name;
}
};
console.log(studentDetails.studentName);
I am calling the getter method... David Miller
Computed Properties with Getter
const rectangle = {
width: 10,
height: 5,
get area() {
return this.width * this.height;
},
get perimeter() {
return 2 * (this.width + this.height);
}
};
console.log("Area:", rectangle.area);
console.log("Perimeter:", rectangle.perimeter);
Area: 50 Perimeter: 30
Getter with Validation
const user = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
get initials() {
return `${this.firstName[0]}.${this.lastName[0]}.`;
}
};
console.log("Full Name:", user.fullName);
console.log("Initials:", user.initials);
Full Name: John Doe Initials: J.D.
Key Points
- Getters are accessed like properties (no parentheses)
- They must return a value
- Useful for computed properties and data transformation
- Can include validation or logging logic
Conclusion
JavaScript getters provide a clean way to access computed properties while hiding implementation details. They're essential for creating intuitive object interfaces and encapsulating logic.
Advertisements
