Is there an ES6+ alternative to doing Object.prototype.hasOwnProperty.call(obj, key)?

Viewed 15914

The most bulletproof way of checking if an object has a certain key is:

Object.prototype.hasOwnProperty.call(obj, key)

This provides certain guarantees: it will only evaluate to true if key is a direct property of obj, and it will work even if obj doesn't have the usual Object as its prototype (for example, if it was created with const obj = Object.create(null)).

But it's a mouthful.

Is there any new syntax/method in ES6 or higher (including polyfillable or Babel-compilable 'proposals') that gives the same guarantees, but in a nicer, more readable way?

2 Answers

Object.hasOwn was added to Object standard API. It is now supported on all major browsers.

Related