🧱 JavaScript Objects & OOP
Estimated reading: 5 minutes 10 views

🧠 JavaScript Getters & Setters Explained – Access & Modify Object Properties

In JavaScript, getters and setters are special methods that provide a way to interact with the properties of objects. They allow us to define custom behavior when accessing or modifying the values of an object’s properties. These methods can be especially useful for data validation, controlling property access, and enhancing code readability.

In this article, we will cover:

  • What are Getters and Setters?
  • How to define and use them in JavaScript
  • Examples to understand the practical implementation
  • Best practices for using getters and setters

📌 What Are Getters and Setters in JavaScript?

A getter is a method that retrieves the value of a property, while a setter is a method that modifies the value of a property. These methods are used to encapsulate the logic behind property access and modification, providing more control over the data.

Here’s the basic syntax:

💡 Getter Syntax:

get propertyName() {
  return this._propertyName;
}

💡 Setter Syntax:

set propertyName(value) {
  this._propertyName = value;
}

💡 Key Facts:

  • Getters are called when accessing a property.
  • Setters are called when assigning a value to a property.
  • Both getter and setter methods can be defined using the get and set keywords, respectively.
  • These methods can be used to perform actions like validation or transformation of data.

📘 Practical Example

Let’s dive into a simple example where we define a getter and setter for an object property.

Example 1: Using Getter and Setter

class User {
  constructor(name) {
    this._name = name; // Private property (conventionally)
  }

  // Getter method
  get name() {
    return this._name.toUpperCase(); // Custom logic: returns name in uppercase
  }

  // Setter method
  set name(value) {
    if (value.length < 3) {
      console.log("Name must be at least 3 characters long.");
    } else {
      this._name = value;
    }
  }
}

const user = new User("John");
console.log(user.name); // JOHN

user.name = "Al"; // Name must be at least 3 characters long.
user.name = "Alice"; // Name set to Alice
console.log(user.name); // ALICE

✅ Line-by-line Breakdown:

  1. Constructor: The constructor initializes the _name property as a private variable (by convention).
  2. Getter Method: The get name() method returns the name in uppercase, encapsulating the logic for how the name should be accessed.
  3. Setter Method: The set name(value) method validates the input, ensuring the name has a minimum length of 3 characters before updating the _name property.

📘 When to Use Getters and Setters?

  1. Data Validation: Ensure that data assigned to a property meets certain criteria.
  2. Encapsulation: Hide the implementation details of how a property is set or retrieved.
  3. Computed Properties: Dynamically compute the value when accessing a property without directly storing it.

Example 2: Encapsulation and Validation

class Rectangle {
  constructor(width, height) {
    this._width = width;
    this._height = height;
  }

  // Getter for the area
  get area() {
    return this._width * this._height;
  }

  // Setter for width
  set width(value) {
    if (value <= 0) {
      console.log("Width must be positive.");
    } else {
      this._width = value;
    }
  }

  // Setter for height
  set height(value) {
    if (value <= 0) {
      console.log("Height must be positive.");
    } else {
      this._height = value;
    }
  }
}

const rect = new Rectangle(5, 10);
console.log(rect.area); // 50

rect.width = -3; // Width must be positive.
rect.height = 0; // Height must be positive.

rect.width = 7;
rect.height = 12;
console.log(rect.area); // 84

✅ Key Points:

  • Area Calculation: The getter for the area property dynamically calculates the area of the rectangle whenever it is accessed.
  • Setter Validation: Both width and height have setter methods that validate the values before updating the properties.

📘 Advantages of Using Getters and Setters

  1. Improved Maintainability: You can modify the behavior of getting or setting a property without changing how the property is accessed elsewhere in your code.
  2. Better Control: Setters and getters allow you to enforce rules, validations, or transformations whenever a property is accessed or modified.
  3. Encapsulation: They provide a way to hide the internal structure of your objects, making the API cleaner and safer for developers.

⚠️ Best Practices

  • Use descriptive names: Choose meaningful names for your getter and setter methods to clarify their purpose.
  • Avoid complex logic in getters: Keep getter methods simple and fast. If a getter becomes too complex, consider using a method instead.
  • Limit side effects in setters: Setters should ideally modify the state of an object. Avoid introducing side effects such as making HTTP calls or logging inside setter methods.

📘 Summary

Getters and setters in JavaScript provide a powerful way to control how properties of an object are accessed and modified. They encapsulate the logic for reading or updating property values, allowing for greater flexibility, validation, and maintenance of your code.

With the ability to use getters for computed properties and setters for validation, JavaScript developers can write cleaner and more reliable code.


❓ Frequently Asked Questions

❓ What is the difference between a getter and a setter in JavaScript?

  • A getter retrieves a property value, while a setter modifies the value of a property. Getters are called when accessing a property, and setters are invoked when assigning a value to a property.

❓ Can I use a getter without a setter?

  • Yes, you can define a getter without a corresponding setter. This is useful when you only need to compute a property dynamically and don’t want to allow modification.

❓ Are getters and setters only for objects?

  • No, getters and setters can be defined on any JavaScript object, including instances of classes, and can be used with properties or computed values.

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — Getters & Setters

Or Copy Link

CONTENTS
Scroll to Top