DEV Community

Cover image for What distinguishes JavaScript's getters from setters?
professional writer
professional writer

Posted on

What distinguishes JavaScript's getters from setters?

We can define object accessors by using getters and setters. In contrast to the latter, which is used to set a property in an object, the former is used to retrieve a property from an object. Let's talk about them using examples.

Getters\sExample

read also : getter and setter in java

In the example that follows, an object called "business" is created, and "Getter" is used to display a property called "company" in the output.

<html>
<body>
<script>
   var business= {
      Name: "pro",
      Country : "nour",
      Company : "google",
      get comp() {
         return this.company;
      }
   };
   document.write(business.company);
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

output

google
Enter fullscreen mode Exit fullscreen mode

Setters

Example

In the example that follows, a new object called "business" is created, and the value of the property "company" is changed from PayPal to SolarCity as displayed in the output.

<html>
<body>
<script>
   var business = {
      Name: "pro",
      Country : "nour",
      company : "google",
      set comp(val) {
         this.company = val;
      }
   };
   business.comp = "SolarCity";
   document.write(business.company);
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

output

SolarCity
Enter fullscreen mode Exit fullscreen mode

Top comments (0)