9-JS OOP: Getters And Setters In Javascript Classes
Tags: javascript, oop, typescript
Published: 2022-11-26 06:29:50

---
title: 9-JS OOP: Getters And Setters In Javascript Classes
published: true
description: 
series: jstsoop
tags: javascript, oop, typescript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ugzrgzbi36kmrh268pk.png
# Use a ratio of 100:42 for best results.
# published_at: 2022-10-25 09:51 +0000
---

## 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:

```ts
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:

```ts
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:

```js
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.

```js
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.

```js
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.

```js
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.

```js
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.

```js
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](https://www.paypal.com/paypalme/hassanzohdy), it will help me to keep going and keep creating more content.

## 😍 Join our community

Join our community on [Discord](https://discord.gg/uBh98KZGGF) 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](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
* [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
* [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

* [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
* [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
* [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

* [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

* [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
* [Node Js 2023 Course: Node With Typescript, The Ultimate Guide](https://dev.to/hassanzohdy/nodejs-course-2023-introduction-to-nodejs-3n4e)
* [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)