What is the difference between getter and setter in JavaScript?


Getter

When a property is accessed, the value gets through calling a function implicitly. The get keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.

Setter

When a property is set, it implicitly calls a function and the value is passed as an argument. With that, the return value is set to the property itself. The set keyword is used in JavaScript. An identifier, either a number or a string is allowed for set.

Example

Here’s an example showing how to implement both getter and setter

Live Demo

<html>
   <body>
      <script>
         var department = {
            deptName: "Finance",
            deptZone: "South",
            deptID: 105,
            get details() {
               return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
            },
            set details(info) {
               var res = info.toString().split(' ');
               this.deptName = res[0] || '';
               this.deptZone = res[1] || '';
               this.deptID = res[2] || '';
            }
         }
         department.details = 'Marketing North 001';
         document.write(department.deptName);
         document.write(department.deptZone);
         document.write(department.deptID);
      </script>
   </body>
</html>

Updated on: 16-Jun-2020

658 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements