Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Getters and Setters

JavaScript Getters and Setters

JavaScript is a versatile programming language that is commonly used in web development. One of the many features of JavaScript is its ability to define getters and setters for object properties. Getters and setters provide a way to encapsulate the implementation details of an object property, while still allowing external code to access and modify its value. In this article, we’ll explore how to define and use getters and setters in JavaScript.

Defining Getters and Setters: Getters and setters are defined using the get and set keywords respectively. When you define a getter or setter, you are actually defining a method that is associated with a particular property of an object. Here’s an example of how to define a getter and setter for a person object:

Javascript




const person = {
    firstName: "John",
    lastName: "Doe",
    get fullName() {
        return `${this.firstName} ${this.lastName}`;
    },
    set fullName(name) {
        const parts = name.split(" ");
        this.firstName = parts[0];
        this.lastName = parts[1];
    },
};
  
console.log(person.fullName); // "John Doe"
  
person.fullName = "Jane Smith";
console.log(person.firstName); // "Jane"
console.log(person.lastName); // "Smith"


Output

John Doe
Jane
Smith

In the example above, we define a person object with two properties, firstName, and lastName. We also define a getter and setter for the fullName property. The getter returns a string that combines the firstName and lastName properties. The setter takes a string as its argument, splits it into two parts, and assigns each part to the firstName and lastName properties.

Now, we’ll explore some more examples of how to use getters and setters in JavaScript:

Example 1: Temperature Conversion: Let’s say we have a temperature object that stores the temperature value in Celsius. We can define a getter and setter for this object that allows us to get and set the temperature value in Fahrenheit. Here’s how we can do this:

Javascript




const temperature = {
    _celsius: 0,
    get fahrenheit() {
        return this._celsius * 1.8 + 32;
    },
    set fahrenheit(value) {
        this._celsius = (value - 32) / 1.8;
    },
};
  
console.log(temperature.fahrenheit); // 32
temperature.fahrenheit = 68;
console.log(temperature._celsius); // 20


Output

32
20

In the example above, we define a temperature object with a private _celsius property, and two getter and setter methods, fahrenheit and fahrenheit=. The get method returns the Fahrenheit equivalent of the Celsius temperature value, and the set method sets the Celsius temperature value based on the Fahrenheit value passed to it.

Example 2: Password Encryption: Let’s say we have a user object that stores the user’s password in plain text. We can define a getter and setter for this object that allows us to encrypt and decrypt the password value. Here’s how we can do this:

Javascript




const user = {
    _password: "",
    get password() {
        return this._password;
    },
    set password(value) {
        this._password = this.encrypt(value);
    },
    encrypt(value) {
        // Encrypt the password value
        return value.split("").reverse().join("");
    },
    decrypt(value) {
        // Decrypt the password value
        return value.split("").reverse().join("");
    },
};
  
console.log(user.password); // ""
user.password = "password123";
console.log(user.password); // "321drowssap"
console.log(user.decrypt(user.password)); // "password123"


Output

321drowssap
password123

In the example above, we define a user object with a private _password property, and two getter and setter methods, password and password=. The get method returns the plain text password value, and the set method encrypts the password value using the encrypt method defined on the object. We also define an encrypt and decrypt method that performs the encryption and decryption of the password value.

Example 3: Validation and Error Checking: Let’s say we have a person object that stores the person’s name and age. We can define a getter and setter for the age property that adds validation and error checking to ensure that the age value is a positive number. Here’s how we can do this:

Javascript




const person = {
    _name: "",
    _age: 0,
    get age() {
        return this._age;
    },
    set age(value) {
        if (typeof value !== "number" || value < 0) {
            throw new Error("Age must be a positive number");
        }
        this._age = value;
    },
};
  
person.age = 25;
console.log(person.age); // 25
// person.age = -10; // throws an error: 
//"Age must be a positive number"


Output

25

Benefits of Getters and Setters: The use of getters and setters provides several benefits in JavaScript programming. One of the main benefits is that it allows you to encapsulate the implementation details of an object property. This means that you can change the internal implementation of a property without affecting the external code that uses the property. In the example above, we could change the fullName getter and setter methods to use a different format for the full name, and external code that uses the fullName property would not need to be changed.

Another benefit of getters and setters is that they allow you to add validation and error-checking to object properties. For example, you could add validation to the fullName setter method to ensure that the string passed to it contains exactly two parts, and throw an error if it does not. This can help to prevent bugs and improve the robustness of your code.

Conclusion: Getters and setters are a powerful feature of JavaScript that allow you to encapsulate the implementation details of object properties, while still providing external code with a way to access and modify their values. By defining getters and setters, you can improve the robustness and maintainability of your code, and make it easier to add validation and error checking to your object properties.

RELATED ARTICLES

Most Popular

Recent Comments