Programming Language
JavaScript
OOPs
Get And Set

Understanding Getters and Setters in JavaScript

In Object-Oriented Programming (OOP), getters and setters are special methods that allow you to control how properties of an object are accessed and modified. They are particularly useful for encapsulating the internal details of an object and providing a controlled way to interact with its properties.

What are Getters and Setters?

  • Getters: These are methods that allow you to access the value of an object’s property.
  • Setters: These are methods that allow you to set or update the value of an object’s property.

Getters and setters provide a way to add custom logic when properties are accessed or changed, like validation or automatic updates to related properties.

Defining Getters and Setters

In JavaScript, you can define getters and setters using the get and set keywords inside a class.

Example:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
 
  // Getter method for fullName
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
 
  // Setter method for fullName
  set fullName(name) {
    const parts = name.split(' ');
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
}
 
// Create an instance of the Person class
const person = new Person('John', 'Doe');
 
// Use the getter to access the full name
console.log(person.fullName); // Output: "John Doe"
 
// Use the setter to change the full name
person.fullName = 'Jane Smith';
 
// Use the getter again to see the updated full name
console.log(person.fullName); // Output: "Jane Smith"

In this example:

  • The fullName getter method combines the firstName and lastName properties into a full name.
  • The fullName setter method splits a full name string and updates the firstName and lastName properties accordingly.

Why Use Getters and Setters?

  • Encapsulation: Getters and setters help keep the internal representation of properties hidden and controlled. For example, you might want to validate the data before setting it or perform some calculation before returning a property value.

  • Data Validation: Setters can be used to enforce certain rules before allowing changes to a property.

  • Computed Properties: Getters can return a value derived from other properties, allowing you to keep your data consistent without manually updating multiple properties.

Example with Validation

Let’s extend our Person class to validate the lastName before setting it:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this._lastName = lastName; // Use _lastName to distinguish from the setter
  }
 
  // Getter for lastName
  get lastName() {
    return this._lastName;
  }
 
  // Setter for lastName with validation
  set lastName(value) {
    if (value.length < 2) {
      console.log('Last name is too short.');
    } else {
      this._lastName = value;
    }
  }
}
 
const person = new Person('John', 'Doe');
 
// Try setting an invalid last name
person.lastName = 'D'; // Output: "Last name is too short."
 
// Set a valid last name
person.lastName = 'Smith';
console.log(person.lastName); // Output: "Smith"

In this example:

The setter for lastName checks that the new value is at least two characters long before updating the property. If it’s too short, an error message is logged instead.

Key Points to Remember

  • Getters: Allow you to access properties while potentially performing additional logic.
  • Setters: Allow you to update properties with the option to validate or modify the data before it’s set.
  • Encapsulation: Getters and setters help you hide the internal workings of a class and provide a controlled interface for interacting with its properties.

Using getters and setters can make your code more robust, maintainable, and easier to understand by centralizing how properties are accessed and modified.