Skip to main content

Archive

Show more

JavaScript Object Getters and Setters

JavaScript Object Getters and Setters

In JavaScript, getters and setters allow you to define object properties that execute a function when accessed (getter) or modified (setter). These special properties provide a flexible way to control how data is retrieved or updated, while offering a clean and readable syntax for interacting with objects.


1. What Are Getters and Setters?

Getters and setters are special methods that let you get or set the value of an object property. They are defined using the get and set keywords inside an object, and they behave like regular properties when accessed or modified.

Here’s a basic example:

const person = {
  firstName: "John",
  lastName: "Doe",
  
  // Getter
  get fullName() {
    return this.firstName + " " + this.lastName;
  },
  
  // Setter
  set fullName(name) {
    const parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

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

// Using the setter
person.fullName = "Jane Smith";
console.log(person.fullName); // Output: Jane Smith

In this example, the fullName property behaves like a regular property but is backed by getter and setter methods. When fullName is accessed, it returns the concatenated name, and when a new name is assigned, the setter splits it into firstName and lastName.


2. Defining Getters in JavaScript

A getter is a method that gets the value of a specific property. It allows you to perform operations or return a computed value whenever a property is accessed.

Example of a Getter

const rectangle = {
  width: 10,
  height: 5,
  
  // Getter for area
  get area() {
    return this.width * this.height;
  }
};

console.log(rectangle.area); // Output: 50

In this example, the area property is a getter that calculates and returns the area of the rectangle every time it’s accessed.

Advantages of Getters

  • They can compute or derive values dynamically when accessed.
  • Provide a clean and intuitive interface for users of the object.
  • Can be used to prevent direct access to internal properties.

3. Defining Setters in JavaScript

A setter is a method that sets the value of a specific property. Setters allow you to define how data should be updated or validated before assigning it to a property.

Example of a Setter

const account = {
  owner: "John",
  balance: 1000,
  
  // Setter for updating balance
  set updateBalance(amount) {
    if (amount < 0) {
      console.log("Invalid amount!");
    } else {
      this.balance += amount;
      console.log("New balance:", this.balance);
    }
  }
};

// Setting the balance using the setter
account.updateBalance = 500; // Output: New balance: 1500
account.updateBalance = -100; // Output: Invalid amount!

In this example, the updateBalance setter ensures that only positive values are added to the balance. If a negative value is passed, the setter logs an error message.

Advantages of Setters

  • Provide control over how properties are set or modified.
  • Can include validation or modification logic before updating a property.
  • Allow for custom side effects when a property is updated.

4. Getters and Setters with Class Syntax

In JavaScript classes, getters and setters can also be defined using the get and set keywords. This makes object-oriented code more modular and maintainable.

Example of Getters and Setters in a Class

class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  
  // Getter for circumference
  get circumference() {
    return 2 * Math.PI * this.radius;
  }
  
  // Setter for updating the radius
  set changeRadius(newRadius) {
    if (newRadius <= 0) {
      console.log("Radius must be positive");
    } else {
      this.radius = newRadius;
      console.log("New radius:", this.radius);
    }
  }
}

const myCircle = new Circle(5);
console.log(myCircle.circumference); // Output: 31.41592653589793
myCircle.changeRadius = 10; // Output: New radius: 10

In this example, the Circle class has a getter for calculating the circumference and a setter for updating the radius with validation. This pattern is useful when encapsulating object data in a class.


5. Using Getters and Setters Together

Getters and setters are often used together to create properties that can be both retrieved and modified with controlled behavior. This combination allows for powerful and flexible object properties.

Example of a Combined Getter and Setter

const product = {
  name: "Laptop",
  price: 1000,
  
  // Getter for formatted price
  get formattedPrice() {
    return "$" + this.price.toFixed(2);
  },
  
  // Setter for updating price
  set updatePrice(newPrice) {
    if (newPrice > 0) {
      this.price = newPrice;
    } else {
      console.log("Invalid price!");
    }
  }
};

// Using getter and setter
console.log(product.formattedPrice); // Output: $1000.00
product.updatePrice = 1200;
console.log(product.formattedPrice); // Output: $1200.00

In this example, the formattedPrice getter returns the price as a formatted string, and the updatePrice setter ensures that only positive values can be assigned to the price.


Conclusion

JavaScript getters and setters provide a powerful mechanism for controlling how object properties are accessed and updated. By using these methods, you can encapsulate your logic, perform validation, and create properties that behave more intelligently. Whether working with simple objects or more complex class-based structures, getters and setters are essential tools in writing clean and maintainable JavaScript code.

Comments