Software Development

Share Post :

HOW TO USE GETTERS AND SETTERS IN JAVASCRIPT

In JavaScript, getters and setters are special functions that allow you to control access to an object’s properties. They provide a way to encapsulate the internal state of an object, allowing you to add logic when getting or setting values. Here’s a guide on how to use getters and setters in JavaScript:

1. Creating a Basic Object:

Start by creating a basic JavaScript object. In this example, we’ll create a Person object with name and age properties.

				
					const person = {
  name: 'John Doe',
  age: 25,
};

				
			

2. Adding Getters and Setters:

Use the Object.defineProperty method to add getters and setters to your object.

Adding a Getter:

				
					Object.defineProperty(person, 'fullName', {
  get: function() {
    return this.name;
  },
});

				
			

Now, when you access person.fullName, it will return the value of person.name

Adding a Setter:

				
					Object.defineProperty(person, 'fullName', {
  get: function() {
    return this.name;
  },
  set: function(value) {
    const [firstName, lastName] = value.split(' ');
    this.name = firstName;
    this.lastName = lastName;
  },
});

				
			

Now, when you set person.fullName, it will split the value into first and last names and update the name and lastName properties.

3. Using Getters and Setters:

Now that you’ve added getters and setters, you can interact with your object as follows:

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

// Using the setter
person.fullName = 'Alice Wonderland';
console.log(person.name); // Output: Alice
console.log(person.lastName); // Output: Wonderland

				
			

4. Class Syntax (ES6):

With the introduction of ES6 classes, you can also use the get and set keywords directly within a class definition.

				
					class Person {
  constructor(name, age) {
    this._name = name;
    this._age = age;
  }

  // Getter
  get fullName() {
    return this._name;
  }

  // Setter
  set fullName(value) {
    const [firstName, lastName] = value.split(' ');
    this._name = firstName;
    this._lastName = lastName;
  }
}

				
			

5. Considerations:

  • Always remember to prefix private properties with an underscore (e.g., _name) to indicate that they should not be accessed directly.
  • Getters and setters provide a way to add additional logic or validation when getting or setting a property.
  • Be cautious about potential side effects when using complex logic within getters and setters.

At ceawebsystems, our commitment to trust, security, and quality extends beyond the finished products we deliver to our clients. As a forward-thinking software development company, we recognize the importance of adopting modern technologies and frameworks to ensure our solutions align seamlessly with the dynamic needs of our client

Open chat
Hello
Can we help you?