JavaScript

Getters and Setters in JavaScript Class

In a JavaScript class, getters and setters are used to get or set the properties values. “get” is the keyword utilized to define a getter method for retrieving the property value, whereas “set” defines a setter method for changing the value of a specific property. When we want to access a property of our JavaScript object, the value returned by the getter method is used, and to set a property value, the setter method is invoked and then we pass the value as an argument that we want to set.

This write-up will discuss getters and setters in JavaScript. Moreover, we will also demonstrate examples related to getter and setter definition usage in the JavaScript class. So, let’s start!

Getters and Setters in JavaScript Class

In the below-given example, we will create an “Employee” class having a constructor. The constructor of the “Employee” class will initialize the Employee “name” to the string passed as an argument :

classEmployee {
    constructor(name) {
        this.name = name;
    }
}

Now, we will create an Employee class object named “employee” and add “Jack” as its name:

let employee = new Employee("Jack");

After doing so, we can access the “name” property of the “employee” object in the following way:

console.log(employee.name);

The output of the above-given program is shown below:

Sometimes, you might not want to access a property directly. That’s where the getter and setter pair come to the play.

Example 1: Getters and Setters in JavaScript Class

To demonstrate the usage of the getter and setter, firstly, we will create an “Employee” class having a “name” property:

classEmployee {
    constructor(name) {
        this.setName(name);
}
}

In the next step, we will define a “getName()” method which will return the value of Employee “name” property:

getName() {
        returnthis.name;
}

Another method, which we are going to add is “setName()”. The setName() method of our Employee class has a “newName” parameter. This method will remove any whitespaces from the value of the “newName” and it will also throw an exception if you have not entered any name:

  setName(newName) {
        newName = newName.trim();
        if (newName === '') {
            throw'Enter an Employee name';
        }
        this.name = newName;
    }

As we have called our “setName()” method in the constructor, so whenever we will create an “Employee” object, the “name” passed as the argument will be taken by the setName() method. Then, the constructor will shift the control flow to the setName() method, and it will set the values passed an argument as “Employee” object name:

let employee = new Employee('Jack Smith');
console.log(employee);

You can also invoke the created “setName()” and “getName()” methods in the following way:

employee.setName('William Smith');
console.log(employee.getName());

The above-given lines of code will set “William Smith” as the name of the “employee” object. Then, the “getName()” method will let you know about the employee name property value:

In the provided example, the setName() and getName() method are working as getter and setter .

Example 2: Getters and Setters in JavaScript Class

For defining getters and setters in the JavaScript class, ES6 also offers a specific syntax. To show you how to use that, we will move into our Employee class:

classEmployee {
    constructor(name) {
        this.name = name;
}
}

Then we will define the getter method by utilizing the keyword “get” which will be followed by the method name. Another thing which we would like to mention here is that the “name” property of our “Employee” class will be change to “_name” to avoid the conflict with the getter and setter:

getname() {
        returnthis._name;
}

To define a setter method, you have to add the “setter” keyword before specifying the method name:

set name(newName) {
        newName = newName.trim();
        if (newName === '') {
            throw' Kindly enter an Employee name';
        }
        this._name = newName;
    }

When you will assign any value to the “name” property of your “Employee” class object, JavaScript will invoke the setter method “name()”:

employee.name = 'Paul Max';

Next, we will call the out getter method in using the below-given syntax:

let empName = employee.name;

Now, when the JavaScript interpreter will execute the above-given lines, it will check of there exists any “name” property in the “Employee” class. It will further search for any method that binds the “name” property if it is not found. In our case, the interpreter will access the getter method and after executing it, it will return the value of “name” property:

In case, if you have not defined a setter method in your JavaScript class, then you will get a TypeError which will state that you cannot set the property “name” of the “Employee” object, as the “Employee” class has only a getter function:

class Employee {
    constructor(name) {
        this.name = name;
    }
    get name() {
        returnthis._name;
}

    //no setter method
}

let employee = new Employee("Stephen Edward");
console.log(employee.name);

Here, we will try to change name of our “employee” object; however, we have not added any setter method in our class:

employee.name = 'Paul Smith';

console.log(employee.name);

As you can see, we have encountered a type error while trying to set the name property value:

Conclusion

Using the get and set keywords, you can easily define the getter and setter methods in a JavaScript class. The getter method returns the property value, whereas, in the setter method, an argument is passed to the setter method, which assigns that specific value to the property of the JavaScript class object. This write-up discussed getters and setters in JavaScript. Moreover, we also demonstrated examples related to getter and setter definition and usage in the JavaScript class.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.