Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 18 - Getters and Setters in JavaScript Objects

What are Getters and Setters?

  • Getters allow you to retrieve object properties in a controlled way.
  • Setters allow you to change object properties while applying validation or transformations.

Instead of directly accessing properties, getters and setters encapsulate data access.


Explanation

  • get is used to retrieve a value.
  • set is used to update a value with logic.
  • These methods allow data validation before updating a property.

Using getters and setters helps keep code clean and maintainable.


Example 1: Using Getters

const person = {
    firstName: "John",
    lastName: "Doe",
    get fullName() {
        return this.firstName + " " + this.lastName;
    }
};

console.log(person.fullName);
// Output: John Doe

Why use a getter?

  • Instead of writing person.firstName + " " + person.lastName, we encapsulate it inside a getter.
  • Now, person.fullName acts like a property but works as a function!

Example 2: Using Setters

const user = {
    _email: "", // Internal property
    get email() {
        return this._email;
    },
    set email(value) {
        if (value.includes("@")) {
            this._email = value;
        } else {
            console.log("Invalid email format!");
        }
    }
};

user.email = "john@example.com"; // Sets email correctly
console.log(user.email); // Output: john@example.com

user.email = "invalidEmail"; // Invalid email format
console.log(user.email); // Output: john@example.com (unchanged)

Why use a setter?

  • The setter validates the email format before saving it.
  • If an invalid email is assigned, it won't update the value.

Try Your Hand

Let's practice using getters and setters.

Steps:

  1. Create a File:

    • Create a new file named lesson18-getters-setters.html.
  2. Write the Code:

    • Copy and paste the following code into your file:
    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Lesson 18 - Getters and Setters</title>
    </head>
    <body>
       <script>
           const product = {
               _price: 0,
    
               get price() {
                   return `$${this._price.toFixed(2)}`;
               },
    
               set price(value) {
                   if (value < 0) {
                       console.log("Price cannot be negative!");
                   } else {
                       this._price = value;
                   }
               }
           };
    
           product.price = 100;  // Set price
           console.log(product.price);  // Output: $100.00
    
           product.price = -50;  // Invalid price
           console.log(product.price);  // Output remains: $100.00
       </script>
    </body>
    </html>
  3. Save the File:

    • Save the file in your folder.
  4. Preview the File:

    • Open the file in your browser and check the console for the output.

Experiment

Try modifying the getter and setter:

  1. Add a discount system:

    const item = {
       _price: 100,
       discount: 10,
    
       get finalPrice() {
           return this._price - (this._price * this.discount / 100);
       }
    };
    
    console.log(item.finalPrice); // Output: 90
  2. Make sure only numbers are accepted:

    const student = {
       _age: 18,
    
       get age() {
           return this._age;
       },
    
       set age(value) {
           if (typeof value === "number" && value > 0) {
               this._age = value;
           } else {
               console.log("Invalid age!");
           }
       }
    };
    
    student.age = 20;  // Valid age
    console.log(student.age); // Output: 20
    
    student.age = "twenty"; // Invalid age
    console.log(student.age); // Output remains: 20

Key Takeaways

Getters make properties look like variables but keep logic hidden. Setters add validation and constraints when modifying values. They protect data integrity and improve maintainability.