JS: Getter Setter Property (accessor)

By Xah Lee. Date: . Last updated: .

What is getter property, setter property

getter and setters together are also known as Accessor Properties.

Getter Property

a special property such that when accessed e.g. obj.color, a function is called implicitly to generate the value (as if there is a method obj.getColor()).

Setter Property

a special property such that when set e.g. obj.color = val, a function is called implicitly to do it (as if there is a method obj.setColor(val)).

Create getter property

syntax:

get keyName () {functionBody}

// object with a getter property rand.

const xx = {
  dog: 1,
  cat: 2,
  get rand() {
    return Math.round(Math.random() * 100);
  },
};

// access property rand
console.log(xx.rand); // 91
console.log(xx.rand); // 37
console.log(xx.rand); // 79

Create setter property

syntax:

set keyName (arg) {functionBody}

// object with a setter property count.
// it updates property _store

const jj = {
 _store: 1,
 set count(x) {
  this._store = x;
  return 7; // return value is ignored
 },
};

jj.count = 3;

console.log(jj._store);
// 3

Getter and setter of the same name

// getter and setter of the same name

const person = {
 _age: 0,

 set age(value) {
  if (typeof value !== "number" || value < 0) {
   throw new Error("Age must be a non-negative number");
  }
  this._age = value;
 },

 get age() {
  return this._age;
 },
};

// using setter
person.age = 30;

// using getter
console.log(person.age);
// 30

console.log(person._age);
// 30

Getter/setter cannot have own value

You cannot have a getter or setter that holds a value itself. (unless you use complex technique such as Closure)

To hold/modify a value, use another property key. A good solution is to create a Symbol key property and have the getter/setter access/modify its value.

Add getter/setter property

Delete getter/setter property

// delete both getter and setter of key gg

const xx = {
 get gg() {
  console.log("getter called");
 },
 set gg(x) {
  console.log("setter called");
 },
};

// delete property gg
Reflect.deleteProperty(xx, "gg");

// verify
console.log(Object.hasOwn(xx, "gg") === false);

Property of the same key, latter overrides

When the same property key appear multiple times, whichever comes later overrides the previous. The only exception is that the same key can be both setter and getter.

// when getter/setter property have the same key as a data property key, whichever comes later overrides the previous

const jj = {
  get kk() {
    3;
  },
  kk: 1,
};

console.log(jj.kk === 1);

Getter setter attributes