Javascript getters and setters in Class Examples


Published on 17 May 2023


Javascript getters and setters in Class Examples

Javascript Getters and Setters Intro

Javascript is a popular programming language that is widely used for developing web applications. One of the key features of Javascript is its support for getters and setters, which are functions used to retrieve and set values of object properties.

Getters and Setters Meaning

Getters and Setters are functions used to retrieve and set the values of object properties in Javascript.
They provide an alternative to traditional property access by allowing developers to control how values are accessed and modified.

Getters and setters are defined using the keywords "get" and "set" respectively, followed by the name of the property they are associated with.

For example:
Consider an object representing a person whose property is name.
Traditional property access would involve accessing these properties directly:

class Person {
  constructor(value) {
    this._name = value;
  }
  get name(){
      return this._name;
  }
  set name(value){
      this._name = value;
  }
}
const person1 = new Person("Paul");
console.log(person1.name); //Paul
person1.name = "John";
console.log(person1.name); //John

Try It Yourself

When developing getter and setter we have to take into account the following:

  • The name of the getter/setter method cannot be the same as the name of the property or name of the defined variable.
  • We can differentiate the name of the method and the property by placing the character _ before the name of the property.
  • When creating a new object with the new keyword we use the constructor method. If we want to use the setter method we must apply it as follows:
    nameObject.setterMethod = property

Benefits to using getters and setters in Javascript

There are several benefits to using getters and setters in Javascript:

  • One of the main advantages is that they provide a way to encapsulate and hide data, preventing direct manipulation of object properties.
    This can be useful for maintaining data integrity and preventing unintended side effects.
  • Another benefit is the ability to perform validation and error handling of property values.
    By defining a setter function, we can check the input value and throw an error if it does not meet certain criteria. This can help to ensure that our code is more robust and less prone to bugs.
  • Getters and Setters provide flexibility in modifying object properties without changing the external interface. This means that we can change the implementation details of our object without affecting the code that uses it. This can be particularly useful for maintaining backward compatibility and avoiding breaking changes.

Using the Get method on Objects

You can use the get method inside an object using the same method for an element of the object.
If one element of the object is an array, the other element of the object will be a get method that can retrieve elements from the array.

  var colorObj = {
    colors: ['yellow', 'black'],
    get firstElement() {
      return this.colors[0];
    }
  };
  console.log('First Element: '+colorObj.firstElement);

We can delete the get method using the "delete" keyword.

Using the Set method on Objects

You can use the Set method inside an object using the same method to set values to another element of the object.
If one element of the object is an array, the other element of the object will be a set method that can add elements to the array.

  var colorObj = {
    colors: ['yellow', 'black'],
    set setValue(val) {
      this.colors.push(val);
    }
  };
  colorObj.setValue = 'Red';
  colorObj.setValue = 'White';
  console.log('All colors: '+colorObj.colors);

Removing getter and setter methods

It is possible to delete a get or set method by using the delete keyword followed by the name of the method to delete.

  var colorObj = {
    colors: ['yellow', 'black'],
    get lastElement() {
      return this.colors[this.colors.length - 1];
    },
    set setValue(val) {
      this.colors.push(val);
    }
  };
  console.log('Adding color red');
  colorObj.setValue = 'Red';
  console.log('All Elements: '+colorObj.colors);
  console.log('Removing method setValue');
  delete colorObj.setValue;
  console.log('Adding color White');
  colorObj.setValue = 'White';
  console.log('All Elements: '+colorObj.colors);
  console.log('Last Element: '+colorObj.lastElement);
  console.log('Removing method lastElement');
  delete colorObj.lastElement;
  console.log('Last Element: '+colorObj.lastElement);
  console.log('All Elements: '+colorObj.colors);

Try It Yourself


Tips on SEO and Online Business

Next Articles

Previous Articles