How to define getter and setter functions 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 call 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: "Marketing",
            deptZone: "North",
            deptID: 101,
            get details() {
               return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
            },
            set details(info) {
               var words = info.toString().split(' ');
               this.deptName = words[0] || '';
               this.deptZone = words[1] || '';
               this.deptID = words[2] || '';
            }
         }
         department.details = 'Marketing North 001';
         document.write(department.deptName);
         document.write(department.deptZone);
         document.write(department.deptID);
      </script>
   </body>
</html>

Ayyan
Ayyan

e

Updated on: 16-Jun-2020

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements