Ben Aston
Ben Aston

Reputation: 55759

Determining if a property is a getter or setter (or both) in JavaScript

Is there a convenience method in ES5 to determine whether a property is a getter or setter, or is the following idiomatic?

var o = {
  get foo() { return 'foo'; },
  set bar(value) {},
  bam: 'bam',
};

function isGetterOrSetter(o, k) {
  var descriptor = Object.getOwnPropertyDescriptor(o, k);
  return !!(descriptor.get || descriptor.set);
}

isGetterOrSetter(o, 'foo'); // true
isGetterOrSetter(o, 'bar'); // true
isGetterOrSetter(o, 'bam'); // false

Upvotes: 2

Views: 79

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074909

No, there's no built-in ES5 (or ES6, I don't think) function that reduces it further than in your question.

Upvotes: 3

Related Questions