What is the “get” keyword before a function in a class - JavaScript?


The get keyword can be used as a getter function like C#, Java and other technologies.

We set a function with get like the following in a class −

class Employee {
   constructor(name) {
   this.name = name;
   }
   get fullName() {
      return this.name;
   }
}

Example

Following is the code displaying an example of get −

class Employee {
   constructor(name) {
      this.name = name;
   }
   get fullName() {
      return this.name;
   }
}
var employeeObject = new Employee("David Miller");
console.log(employeeObject.fullName);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo299.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo299.js
David Miller

Updated on: 09-Nov-2020

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements