Member-only story

Javascript get method (When and how to use it)

Vinodh Thangavel
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.

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet