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
What is the "get" keyword before a function in a class - JavaScript?
The get keyword in JavaScript creates a getter method that allows you to access a function like a property. When you call the getter, it executes the function and returns its value without using parentheses.
Syntax
class ClassName {
get propertyName() {
// return some value
}
}
Basic Example
Here's how to define and use a getter method:
class Employee {
constructor(name) {
this.name = name;
}
get fullName() {
return this.name;
}
}
var employeeObject = new Employee("David Miller");
console.log(employeeObject.fullName); // No parentheses needed
David Miller
Getter vs Regular Method
The key difference is how you access them:
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Getter - accessed like a property
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
// Regular method - requires parentheses
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person = new Person("John", "Doe");
console.log(person.fullName); // Getter - no parentheses
console.log(person.getFullName()); // Method - requires parentheses
John Doe John Doe
Practical Use Case
Getters are useful for computed properties and data validation:
class Circle {
constructor(radius) {
this._radius = radius;
}
get radius() {
return this._radius;
}
get area() {
return Math.PI * this._radius * this._radius;
}
get circumference() {
return 2 * Math.PI * this._radius;
}
}
const circle = new Circle(5);
console.log(`Radius: ${circle.radius}`);
console.log(`Area: ${circle.area.toFixed(2)}`);
console.log(`Circumference: ${circle.circumference.toFixed(2)}`);
Radius: 5 Area: 78.54 Circumference: 31.42
Key Points
- Getters are accessed like properties (no parentheses)
- They execute code when accessed, unlike simple properties
- Useful for computed values and encapsulation
- Cannot take parameters
- Often paired with setter methods
Conclusion
The get keyword creates getter methods that behave like properties but execute functions. Use getters for computed values and to provide clean, property-like access to class data.
Advertisements
