Member-only story
Javascript get method (When and how to use it)
1 min readJul 4, 2023
get method is used in javascript objects both plain and class based when the function doesn’t take any arguments, just a return value
Plain JS object
const user = {
firstName: 'Vinodh',
lastName: 'Thangavel',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
};
console.log(user.fullName); // Vinodh Thangavel
get
keyword is added to the function name,
user.fullName
the getter function is called as a property,
Class
class User {
constructor(private firstName, private lastName) {}
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
const user = new User('Vinodh', 'Thangavel');
console.log(user.fullName); // Vinodh Thangavel
Only the syntax is the difference, but the functionalities remains the same.
Violations
- We should not call it as
user.fullName()
— Error: user.fullName is not a function - We cannot add arguments to the function, as we cannot send arguments while accessing, if arguments are added, it will be a violation.
get fullName(arg1)
— Error: Getter must not have any formal parameters.