What are Getters and Setters?
Getters and setters are methods that are used to get and set the value of a property member in a class.
So a getter
method is a method that is prefixed with get
keyword, and it allows us to get a certain value when a user tries to access that getter
property.
An example of a getter
method:
class Human {
private _name: string = 'Hasan';
get name() {
return this._name;
}
}
Here we defined get name()
this is a getter method, it allows us to return whatever we want, in our case we're going to return our private property _name
.
Any getter method, does not take any parameters, and it returns a value.
On the other hand, a setter
method is a method that is prefixed with set
keyword, and it allows us to set a certain value when a user tries to set that setter
property.
An example of a setter
method:
class Human {
private _name: string = 'Hasan';
set name(name: string) {
this._name = name;
}
}
Here we defined set name(name: string)
this is a setter method, it allows us to set whatever we want, in our case we're going to set our private property _name
.
Any setter method, takes a parameter, which is the value that we want to assign and it does not return a value.
Using typescript is not necessary, i'm using it just to show you the syntax.
Why do we need Getters and Setters?
Getters and setters are used to get and set the value of a property member in a class, this will give us more control over the value of the property member.
Example of usage
Let's see an example:
class Human {
_name = '';
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
}
const me = new Human();
me.name = 'Hasan';
console.log(me.name);
Here we have a class called Human
that has a property member called _name
and we have a getter and a setter for this property member.
But why not just use the property member directly?
Well, we can use the property member directly but we will lose the control over the value of the property member.
For example, we want to add birthDate
property which allows the user define his/her birth date, but in the mean time, we want to calculate the age of the user based on the birth date.
class Human {
_name = '';
_birthDate = '';
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
get birthDate() {
return this._birthDate;
}
set birthDate(value) {
this._birthDate = value;
}
}
const me = new Human();
me.name = 'Hasan';
me.birthDate = '1990-01-01';
console.log(me.name);
console.log(me.birthDate);
Nothing new here, we just added the birthDate
property member and we have a getter and a setter for it.
Now let's add a new property member called age
and we will calculate the age based on the birthDate
property member.
class Human {
_name = '';
_birthDate = '';
_age = 0;
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
get birthDate() {
return this._birthDate;
}
set birthDate(value) {
this._birthDate = value;
// Calculate the age based on the birth date
const birthDate = new Date(value);
const today = new Date();
this._age = today.getFullYear() - birthDate.getFullYear();
}
get age() {
return this._age;
}
}
const me = new Human();
me.name = 'Hasan';
me.birthDate = '1990-01-01';
console.log(me.name); // Hasan
console.log(me.birthDate); // 1990-01-01
console.log(me.age); // 33
This is where getters and setters are useful, we can calculate the age based on the birth date and we can control the value of the property member.
We can also use getters and setters to validate the value of the property member.
class Human {
_name = '';
_birthDate = '';
_age = 0;
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
get birthDate() {
return this._birthDate;
}
set birthDate(value) {
if (typeof value !== 'string') {
throw new Error('Birth date must be a string');
}
this._birthDate = value;
// Calculate the age based on the birth date
const birthDate = new Date(value);
const today = new Date();
this._age = today.getFullYear() - birthDate.getFullYear();
}
get age() {
if (! this._age) {
throw new Error('Age is not available, please set the birth date first');
}
return this._age;
}
}
const me = new Human();
me.name = 'Hasan';
console.log(me.name); // Hasan
me.birthDate = 1990; // Error: Birth date must be a string
console.log(me.age); // Error: Age is not available, please set the birth date first
In that sense, we checked the data type of the birthDate
property member and we also checked if the age
property member is available or not.
Combining multiple properties when using getters
Another way to use getter
methods is to combine multiple properties when using getters.
For example, we've the firstName
and lastName
properties, and we want to combine them when we use the fullName
property.
class Human {
_firstName = '';
_lastName = '';
get firstName() {
return this._firstName;
}
set firstName(value) {
this._firstName = value;
}
get lastName() {
return this._lastName;
}
set lastName(value) {
this._lastName = value;
}
get fullName() {
return `${this._firstName} ${this._lastName}`;
}
}
const me = new Human();
me.firstName = 'Hasan';
me.lastName = 'Khan';
console.log(me.fullName); // Hasan Khan
Is it practical in our real world projects?
The answer is Yes of course, we can use getters and setters in our real world projects, not so much but we can use them, for example that fullName
property is easier to use in our code, especially if we are working with list of keys and we just want to loop over these keys to get its values and display it.
const keys = ['firstName', 'lastName', 'fullName', 'birthDate', 'age'];
for (const key of keys) {
console.log(me[key]);
}
So i won't get bothered by checking if the key is a method or a property member, i can just use it directly.
🎨 Conclusion
In this article, we learned about getters and setters in javascript, we learned why we need them and how we can use them.
☕♨️ Buy me a Coffee ♨️☕
If you enjoy my articles and see it useful to you, you may buy me a coffee, it will help me to keep going and keep creating more content.
😍 Join our community
Join our community on Discord to get help and support.
📚 Bonus Content 📚
You may have a look at these articles, it will definitely boost your knowledge and productivity.
General Topics
- Event Driven Architecture: A Practical Guide in Javascript
- Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript
- After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
Packages & Libraries
- Collections: Your ultimate Javascript Arrays Manager
- Supportive Is: an elegant utility to check types of values in JavaScript
- Localization: An agnostic i18n package to manage localization in your project
React Js Packages
Courses (Articles)
Top comments (0)