Skip to main content

How to Use Getters and Setters in JavaScript

Getters and setters exist in most object-oriented programming languages, including JavaScript. They are code constructs that help developers access the properties of objects in a secure way. With getters, you can access (“get”) the values of properties from external code, while setters let you change (“set”) their values. In this tutorial, we’ll show you how you can create getters and setters in JavaScript.

How to Create Getters and Setters in JavaScript

A JavaScript object can have multiple properties and methods that store static data and dynamic functionality. Properties are static key-value pairs, while methods are functions specific to the object.

For example, Car.color could be a property, while Car.drive() could be a method of the Car object. With a getter, you can access the color property of the Car object and with a setter, you can modify its value (for instance, from blue to black).

With getters and setters, you can only get and set the values of properties but not methods, as methods are not static.

You can create getters and setters in three different ways:

  1. with the default method syntax (getter and setter methods),
  2. with the get and set keywords,
  3. with the Object.defineProperty() method.

Getter Methods

The easiest way to get the properties of an object is by defining a getter using the default method syntax for each of the properties. Let’s see an example of how to create getters using this technique. The myCar object has two properties: color and make. This is how you can create it using an object literal:

var myCar = {   
   color: "blue",
   make: "Toyota"
};

If you wanted, you could access the color and make properties directly with the following code:

myCar.color;
// blue

myCar.make;
// Toyota

Although this technique works, using getters rather than directly calling properties has a number of advantages. For instance,  you can perform operations or checks (e.g. an if-else statement) on the property before retrieving its value. 

You can define getter methods for the color and make properties in the following way:

var myCar = { 
   color: "blue", 
   make: "Toyota",

   getColor: function() {
       return this.color;
   },
   getMake: function() {
       return this.make;
   } 
};

The getters above make use of the this keyword that refers to the object the property belongs to (myCar in the example). The return statements inside the getters essentially mean that “return the value of the color / make property of this object”.

To get the properties of the myCar object, you need to call the getter methods:

myCar.getColor();
// blue

myCar.getMake();
// Toyota

If you want, you can also add extra logic to your getter methods. For example, you can get the values of both properties at the same time by creating a getCar() method:

var myCar = { 
    color: "blue", 
    make: "Toyota", 
    
    getCar: function() { 
         return "This is a " + this.color + " " + this.make + "."; 
    } 
};

myCar.getCar();
// This is a blue Toyota.

Setter Methods

Besides getters, you can also create setters using JavaScript’s default method syntax. Below, you can see how the setColor() and setMake() methods compare to the previously declared getters.

var myCar = { 

    /* Properties */
    color: "blue", 
    make: "Toyota", 
    
    /* Getter methods */
    getColor: function() { 
	return this.color; 
    }, 
    getMake: function() { 
	return this.make; 
    },  

    /* Setter methods */
    setColor: function(newColor) {
        this.color = newColor;
    },
    setMake: function(newMake) {
	this.make = newMake;
    }
};

As setters exist for the reason of changing the values of properties, they take the new values of the properties (newColor and newMake) as parameters.

You can call the setter methods in the following way:

myCar.setColor("red");
myCar.setMake("Audi");

myCar.getColor();
// red

myCar.getMake();
// Audi

After setting the new values, you can check with the getters if they have been properly changed.

The get Keyword

The get keyword is another way of creating getters. You can define getters for the myCar.color and myCar.make properties with the get keyword in the following way:

var myCar = { 
    /* Data properties */
    defColor: "blue", 
    defMake: "Toyota",
    
    /* Accessor properties (getters) */ 
    get color() { 
         return this.defColor; 
    }, 
    get make() { 
         return this.defMake; 
    }    
};

/* Calling the getter accessor properties */
myCar.color;
// blue

myCar.make;
// Toyota

The most important thing to remember about the get keyword is that it defines an accessor property, rather than a method. So, it can’t have the same name as the data property that stores the value it accesses. In the code above, defColor and defMake are the data properties, while color and make are the accessor properties.

This is also why you need to call the getter with a property syntax that doesn’t use parentheses after the name of the getter (e.g. myCar.color).

As the get keyword is not supported by older Internet Explorers (IE8-), if you need to support legacy browsers, rather use getter methods.

The set Keyword

The set keyword defines an accessor property that allows you to change the value of a data property. Here’s how you can add setters to the above code:

var myCar = {
    /* Data properties */
    defColor: "blue", 
    defMake: "Toyota",
    
    /* Accessor properties (getters) */
    get color() { 
         return this.defColor; 
    }, 
    get make() { 
         return this.defMake; 
    },
    
    /* Accessor properties (setters) */
    set color(newColor) {
	this.defColor = newColor;
    },
    set make(newMake) {
	this.defMake = newMake;
    }
};

/* Calling the setter accessor properties */
myCar.color = "red";
myCar.make = "Audi";

/* Checking the new values with the getter accessor properties */
myCar.color;
// red

myCar.make;
// Audi

You can use the same names (color and make) for the setters as for the getters, but with parameters (newColor and newMake). The parameters will allow you to pass the new values to the properties. You can call the setters by using the assignment operator (equals sign) and assigning the new value to them.

The biggest advantage of using the get and set keywords is that you can keep data properties private. As the getters and setters have different names (color and make), you won’t accidentally override the value of the data properties (defColor and defMake) with external code.

The Object.defineProperty() method

You can use the defineProperty() method of the global Object to add getters and setters to an already existing object. Say, you already have the myCar object holding the defColor and defMake data properties. Later, you can add getters and setters to it using the Object.defineProperty() method as follows:

/* Original object you already have */
var myCar = { 
    defColor: "blue", 
    defMake: "Toyota"
};

/* Adding a getter and setter to defColor */
Object.defineProperty(myCar, "color", {
	get: function() { 
         return this.defColor; 
    },
	set: function(newColor) {
		this.defColor = newColor;
	},
});

/* Adding a getter and setter to defMake */
Object.defineProperty(myCar, "make", {     
    get: function() { 
         return this.defMake; 
    },
	set: function(newMake) {
		this.defMake = newMake;
	}
});

/* Checking the value of the properties with the getters */
myCar.color;
// blue

myCar.make;
// Toyota

/* Modifying the values with the setters */
myCar.color = "red";
myCar.make = "Audi";

/* Checking the modified properties with the getters */
myCar.color;
// red

myCar.make;
// Audi 

In fact, you can’t only use Object.defineProperty() to modify an existing object but you can add getters and setters to a newly defined object as well. This solution can be useful when you want to make use of the built-in properties of Object.defineProperty(), such as writable or configurable (see the full list in the MDN docs).

Conclusion

You don’t necessarily have to use getters and setters when creating a JavaScript object, but they can be helpful in many cases. The most common use cases are (1) securing access to data properties and (2) adding extra logic to properties before getting or setting their values.

If you want to learn more about the basics of JavaScript programming also have a look at our previous articles on how to use arrow functions and the 4 ways of creating JS objects.

If you’d rather read a more hands-on tutorial check out our step-by-step guide on how to build a countdown timer in pure JavaScript, too.

Wp-dd.com

WordPress Design, WordPress Development, cPanel Hosting, Web Design, Web Development, Graphic Design, Mobile Development, Search Engine Optimization (SEO) and more.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.