Computer >> Computer tutorials >  >> Programming >> Javascript

What is the difference between Getters and Setters in JavaScript?


Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object. Let's discuss them through examples.

Getters

Example

In the following example, an object named "business" is created and using "Getter" a property called "company" is displayed in the output.

<html>
<body>
<script>
   var business= {
      Name: "Musk",
      Country : "America",
      Company : "PayPal",
      get comp() {
         return this.company;
      }
   };
   document.write(business.company);
</script>
</body>
</html>

output

paypal


Setters

Example

In the following example, an object named "business" is created and using "Setter" the value of property called "company" is changed from PayPal to SolarCity as shown in the output.

 

<html>
<body>
<script>
   var business = {
      Name: "Musk",
      Country : "America",
      company : "PayPal",
      set comp(val) {
         this.company = val;
      }
   };
   business.comp = "SolarCity";
   document.write(business.company);
</script>
</body>
</html>

Output

SolarCity