Search⌘ K

Get & Set

Explore how JavaScript's get and set keywords allow you to access and modify object properties as if they were simple data fields. Understand the difference between calling methods and accessing properties, and learn to write cleaner, more intuitive object code.

Using get Keyword

Let’s revise our knowledge for this keyword:

Javascript (babel-node)
var employee = {
name: 'Joe',
age: 28,
designation: 'developer',
//function returning designation of the employee
display() {
return this.designation //using this to refer to the "employee" object
}
}
//this will display the designation
console.log(employee.display())

Here, the function display() was being used to get the value of the property designation. Another way to do this is by using the get keyword.

Example

Let’s take a look at an example implementing the get keyword.

Javascript (babel-node)
var employee = {
name: 'Joe',
age: 28,
designation: 'developer',
//function returning designation of the employee
get display() {
return this.designation //using this to refer to the "employee" object
}
}
//this will display the designation
console.log(employee.display)

Explanation

You must be wondering what the difference is ...