JavaScript Object Accessors

JavascriptWeb DevelopmentObject Oriented Programming

The getter and setter keyword are used for accessing the objects. The getter return value is used when a property is being accessed and the setter takes an argument and sets the property value inside the object to that passed argument.

Following is the code for accessing objects in JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
<h1>JavaScript Object Accessors</h1>
Enter a number <input class="num" type="number" />
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
Click on the above button to set the age value and display it
   let sampleEle = document.querySelector(".sample");
   let testObj = {
      age: "",
      set AGE(val) {
         this.age = val;
      get AGE() {
         return this.age;
   document.querySelector(".Btn").addEventListener("click", () => {
      let number = document.querySelector(".num").value;
      testObj.AGE = number;
      sampleEle.innerHTML = "AGE = " + testObj.AGE;


On entering a number and clicking on ‘CLICK HERE’ button −

Updated on 11-May-2020 13:55:31