Skip to main content
JavaScriptWeb Dev

Setters and Getters in JavaScript – part 1

By August 19, 2020July 20th, 2022No Comments
getters and setters in JavaScript

Accessors: Getters and Setters

This is part 1  of a brief introduction to getters and setters in JavaScript. Getters and Setters are ES5 features. Objects have two types of properties:

  1. Static data property
  2. Accessor property

So far we have come across static data properties in the objects that we have been making. For example:

let blackLivesMatter = {
status: true,
usecase: 'daily'
}

In this object, status and usecase properties are static. So what then are accessor properties? Accessor properties are functions that will execute on either getting or setting a value. The two types of accessor properties are: Getter property: Upon getting a property of an object such as car.color the value of the property will be generated implicitly by calling a function. The getter works upon reading a property. Setter property: When a property is set for example on an object car.color = ‘red’ a function is executed implicitly passing the value of a property, in this case ‘red’ as an argument to the function. The return value of the function is set to the property. The setter works upon assignment of a property  

carrying on from part 1 ..

Getters in JavaScript

Getters are functions that retrieve a value from static properties from an external source. You can only access properties and cannot access methods as they are functions of an object or class and are not static. There are three ways you can use getters and setters: 1. Default method syntax 2. get  keyword 3. Object.defineProperty() method

We will now discuss the above three in detail.

1. Default method syntax

We can define a getter by using the default method syntax in order to retrieve the property of an object. In order to make this clear have a look at the following example:

let truck = {
    color: 'red',
    make: 'Peterbilt',
    getDetails: function() {
        return(this.color)
    }
};

In the example above, the truck object has one getter method getDetails().The this keyword references the object that the property belongs to (truck). The return statement inside the getter method will return the value of the color property. To access the color property of the truck object, call the getDetails() method on the truck object like so:

truck.getDetails();

The default method syntax can also be used for setters. Setters will set the property of the object to the value passed in to the setter method. For example:

let truck = {
    color: 'red',
    make: 'Peterbilt',
    getDetails: function() {
        console.log(this.color)
    },
    setDetails: function(newColor) {
        this.color = newColor;
    }
};

The setDetails() method takes a parameter newColor and sets the value of the color property to the parameter passed in. Let’s change the color of truck :

object:truck.setDetails('blue');

Let’s check if the setter method worked properly by using the getter method

getDetails():
truck.getDetails();//blue

The getDetails()method will return blue therefore indicating that the setDetails() method did indeed set the value of the color property to blue. Now let’s talk about the get and set keywords.

2. Get keyword

The get and set keywords can be used to explicitly create getters and setters. The following sections will discuss both.

Get Keyword:

The get keyword will explicitly create a getter. It will define an accessor property rather than using a method. This means it cannot have the same name as the data property whose value it is used to gets/retrieve. Let’s have a look at an example to make this clear:

const randomNum = {
    number1: 1,
    get number2() {
        return Math.floor(Math.random() * 100);
    }
};
console.log(randomNum.number2);

In the method the name of the property number1 and name of the accessor property defined by the get keyword (number2) are different. Upon getting number2, its value will be computed to a random number between the numbers zero to hundred using the Math.random and Math.floor methods. Therefore, the value of the number2 property will be generated implicitly by calling a function.

3.Object.defineProperty() method

This method is part of ES5. It is used to define properties, getters and setters on an object that has already been declared, you can use the defineProperty() method on the global Object. This might seem a bit redundant as properties are defined at the time of an object’s declaration. However, this method allows us to define a property’s descriptor which is akin to a property’s meta data.

Syntax: Object.defineProperty(object, property, descriptor)

The first argument is the object on which to define a getter or setter. The second argument is the name of the property which is to be defined and, the third argument is the descriptor for the property. Let’s have a look at an example to see how this works. Firstly, we will declare and instantiate a new object called truck:

let truck = {};

Now let’s use the Object.defineProperty() method to add a data property to the truck object:

Object.defineProperty(truck, "color", {
  configurable: false,
  enumerable: false,
  writable: false,
  value: "red"
});
  1. Let’s examine the code block above: The first argument passed to the Object.defineProperty() method is the truck object.
  2. The second argument is the name of the property which we have called color.
  3. The third argument is the color property’s descriptor. Descriptors allow modification of a property.
  4. The configurable attribute is set to false. Configurable alludes to whether a property can be deleted or changed.
  5. The second attribute is enumerable. This will dictate whether the color property can be enumerated using the for-in loop.
  6. The third descriptor attribute is writable. This will dictate whether the color property’s value can be changed using the assignment = operator.
  7. And lastly the value attribute’s value will be the color property’s value which is “red”. Let’s check the color property of the truck object by logging it to the console:
console.log(truck.color); // "red"
 

Setters in JavaScript. Check out parts 1 and  2

Setters in JavaScript

There are three ways you can use  setters: 1. Default method syntax 2. get  keyword 3. Object.defineProperty() method

We will now discuss the above three in detail.

1. Default method syntax

The default method syntax can also be used for setters. Setters will set the property of the object to the value passed into the setter method. For example:

let truck = {
    color: 'red',
    make: 'Peterbilt',
    getDetails: function() {
        console.log(this.color)
    },
    setDetails: function(newColor) {
        this.color = newColor;
    }
};

The set details() method takes a parameter new color and sets the value of the color property to the parameter passed in. Let’s change the color of the truck object:

truck.setDetails('blue');

2. Set keyword

The set keyword can be used in lieu of the default method syntax for setting the value of a property. The set keyword will define an accessor property whose value you can set. For example:

const randomNum = {
    number1: 1,
    get number2() {
        return Math.floor(Math.random() * 100);
    },
    set num(x) {
        this.number1 = x;
    }
};

In the example, we have used the set keyword to define a num accessor property that takes x as a parameter. It will set the value of this.number1 property to x. Let’s set the num accessor property to a value of 10.

randomNum.num = 10;

Upon logging the number1 property of the random object, we see 10 logged to the console:

console.log(randomNum.number1);

3.Object.defineProperty() method

Let’s have a look at an example to see how this works. Firstly, we will declare and instantiate a new object called truck:

let truck = {};

Now let’s use the Object.defineProperty() method to add a data property to the truck object:

Object.defineProperty(truck, "color", {
 configurable: false,
 enumerable: false,
 writable: false,
 value: "red"
});
  •  The first argument passed to the Object.defineProperty() method is the truck object.
  • The second argument is the name of the property which we have called color.
  • The third argument is the color property’s descriptor. Descriptors allow modification of a property.
  • The configurable attribute is set to false. Configurable alludes to whether a property can be deleted or changed.
  • The second attribute is enumerable. This will dictate whether the color property can be enumerated using the for-in loop. 218
  • The third descriptor attribute is writable. This will dictate whether the color property’s value can be changed using the assignment = operator.
  • And lastly the value attribute’s value will be the color property’s value which is “red”.

Let’s check the color property of the truck object by logging it to the console:

console.log(truck.color); // "red"

The Object.defineProperty() method can also be used to define getters and setters on an existing object. The code below demonstrates a setter method of the truck object:

Object.defineProperty(truck, "setColor", {
  set: function(newColor) {
  this.color = newColor;
 }
});

The property setColor is a setter that will set the color of the truck to the new value assigned to it. For example, let’s change the color property of the truck to blue:

truck.setColor = ('blue')

A console.log reveals that the color is still red:

console.log(truck.color); // "red"

This is because the writable descriptor is set to false. Let’s add another setter to this object for practice:

Object.defineProperty(truck, "setBrand", {
  set: function(brand) {
  this.brand = brand;
 }
});

This will create a brand property and now let’s set its value:

truck.setBrand = 'Peterbilt';

Leave a Reply