JavaScript(JS) Getters and Setters

In JavaScript, getters and setters are special functions that are used to define the behavior of object properties when they're accessed or modified. Getters and setters allow you to control how your object properties are accessed and manipulated, which can be useful for ensuring data integrity and encapsulation.

Here's an example of using getters and setters in JavaScript:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  set fullName(name) {
    const [firstName, lastName] = name.split(" ");
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

const john = new Person("John", "Doe");

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

john.fullName = "Jane Smith";
console.log(john.firstName); // Output: "Jane"
console.log(john.lastName); // Output: "Smith"
Sourc‮i.www:e‬giftidea.com

In this example, we have a Person class with firstName and lastName properties, as well as a fullName property that is defined using a getter and a setter. The getter returns the full name of the person by concatenating the firstName and lastName properties, while the setter takes a full name string as an argument, splits it into its first and last name components, and sets the corresponding properties.

When we access the fullName property using the john.fullName syntax, the getter function is automatically called and returns the full name. When we assign a new value to the fullName property using the john.fullName = "Jane Smith" syntax, the setter function is automatically called and sets the firstName and lastName properties based on the new full name value.

Getters and setters are useful for controlling the behavior of object properties, but they can also add complexity to your code. Use them judiciously, and only when necessary to ensure data integrity or encapsulation.