JS Getters and Setters

In JavaScript ES5(2009), there are getter and setter defined using keyword get and set. The getter will get the value and the setter will set the value of the property.

These are computed properties for the object and might be useful when you want to convert object property into something before using it.

Getters

The getter is defined using keyword get. Consider the following code.

//Our object 
var car = {
carName: "volvo",
carModel: "xc60",
get carmodel(){
  return this.carModel.toUpperCase();
}
};
console.log(car.carmodel);
//output = XC60

In the code, above we created an object called car. The object has carModel property. You can access the object getter just like any other property.

Here is an example

console.log(car.carmodel)

This will result in XC60 which is uppercase version of xc60.The getter converts the original object property called carModel.

Setters

The setters are compute-able property that update the original object property.

Consider the following example

//Our object 
var car = {
carName: "volvo",
carModel: "xc60",
//my Getter
get carmodel(){
  return this.carModel.toUpperCase();
},
//my Setter
set newcarmodel(model){
this.carModel = model;
};
//set a new car model
car.newcarmodel = "sc60";
console.log(car.carmodel);
//output = SC60 (in uppercase)

In the above code, we have called the setter and assigned a new car model to the original model property of the car.

car.newcarmodel = "sc60";

Note that the output is through getter car.carmodel which change the output to uppercase.

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag