What Is Meant by "Accessor Property" in JavaScript?

In JavaScript, an "accessor property" is a type of object property that has the following attributes (or property descriptors):

  • get — a getter function for the property;
  • set — a setter function for the property;
  • enumerable — if true, the property will show up during enumeration of the object properties;
  • configurable — if false, it prevents deletion of the property as well as any changes to the object property's descriptors.

These (optional) property descriptors exist for all accessor properties. For example, you can use the Object.getOwnPropertyDescriptor() method to check an object's descriptors like so:

const obj = {
  get foo() { return this._foo; },
  set foo(value) { this._foo = value; },
};
const descriptors = Object.getOwnPropertyDescriptor(obj, 'foo');

console.log(descriptors); // { enumerable: true, configurable: true, get: ƒ, set: ƒ }

As you can see from the example above, the getter and setter for the property "foo" are defined while the enumerable and configurable properties default to true. You would use the getter and setter on the object property like so:

console.log(obj.foo); // undefined

obj.foo = 'bar';

console.log(obj.foo); // 'bar'

Please note that you may also have accessor descriptors with only a getter and no setter, or vice versa. However, if you do not specify (to the very least) one of them, then the object property is treated as a "data property".

You can also create an object property using the Object.defineProperty() method, which would give you finer control over the property descriptors. However, you should be aware that if you use the Object.defineProperty() method (or Object.create), then enumerable and configurable properties would default to false. Consider for example, the following:

const obj = {};
const objDescriptor = {
  get() { return this._foo; },
  set(value) { this._foo = value; },
};

Object.defineProperty(obj, 'foo', objDescriptor);

const descriptors = Object.getOwnPropertyDescriptor(obj, 'foo');

console.log(descriptors); // { enumerable: false, configurable: false, get: ƒ, set: ƒ }

You would use the getter and setter on the object property like so:

console.log(obj.foo); // undefined

obj.foo = 'bar';

console.log(obj.foo); // 'bar'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.