Mastering Getter and Setter in JavaScript

JavaScript provides powerful mechanisms for controlling access to object properties through getters and setters. These features allow developers to enforce encapsulation, validate data, and execute custom behavior when accessing or modifying object properties. In this article, we'll explore three different ways of implementing getters and setters in JavaScript, along with their respective advantages and use cases.

1. Using Getters and Setters with ES6 Classes:

ES6 introduced class syntax, making it easier to define object blueprints. With ES6 classes, defining getters and setters is straightforward:

class User {
    constructor(email, password) {
        this.email = email;
        this.password = password;
    }

    get email() {
        return this._email.toUpperCase();
    }

    set email(value) {
        this._email = value;
    }

    get password() {
        return `${this._password}hitesh`;
    }

    set password(value) {
        this._password = value;
    }
}

const hitesh = new User("h@hitesh.ai", "abc");
console.log(hitesh.email); // Output: H@HITESH.AI

2. Defining Getters and Setters with Object.defineProperty:

For more fine-grained control over property attributes, Object.defineProperty can be used. This approach allows specifying additional property descriptors such as configurability, writability, and enumerable. Here's how you can use Object.defineProperty:

function User(email, password) {
    this._email = email;
    this._password = password;

    Object.defineProperty(this, 'email', {
        get: function () {
            return this._email.toUpperCase();
        },
        set: function (value) {
            this._email = value;
        }
    });

    Object.defineProperty(this, 'password', {
        get: function () {
            return this._password.toUpperCase();
        },
        set: function (value) {
            this._password = value;
        }
    });
}

const chai = new User("chai@chai.com", "chai");
console.log(chai.email); // Output: CHAI@CHAI.COM

3. Utilizing Getters and Setters with Object Literals and Object.create:

JavaScript also allows defining getters and setters directly within object literals or by using Object.create for prototypal inheritance. This approach is particularly useful when working with singleton objects or when extending existing objects:

const User = {
    _email: 'h@hc.com',
    _password: "abc",

    get email() {
        return this._email.toUpperCase();
    },

    set email(value) {
        this._email = value;
    }
};

const tea = Object.create(User);
console.log(tea.email); // Output: H@HC.COM

Conclusion:

In JavaScript, getters and setters provide a flexible way to manage object properties, enabling developers to enforce data validation, execute custom logic, and maintain encapsulation. Whether you prefer ES6 classes, Object.defineProperty, or object literals with Object.create, understanding these different approaches empowers you to choose the most suitable method for your specific use case. Experiment with each method and leverage the power of getters and setters to write cleaner, more maintainable JavaScript code.

References:

https://youtube.com/playlist?list=PLu71SKxNbfoBuX3f4EOACle2y-tRC5Q37&si=hmp4H96RF8eTdTkn