Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 472
callum Avatar asked Jul 20 '17 13:07

callum


People also ask

What is object prototype hasOwnProperty?

prototype. hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

Is hasOwnProperty necessary?

Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on. It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.

What's the difference between the in operator and the hasOwnProperty method in objects?

So what's the difference between the two? The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.

How properties are assigned to an object in JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.


1 Answers

I'm not aware of any syntactical sugar for this. But you shouldn't need to use this very often1, so writing it out occasionally shouldn't be too bad. An equivalent shorter version would be

({}).hasOwnProperty.call(obj, key)

If you really need to use it more often, just define a helper function:

const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
const hasOwn = Function.prototype.call.bind(Object.prototype.hasOwnProperty);

1: In most cases, you can omit the check, use in instead, or should be using a Map with its comfortable has method.

like image 102
Bergi Avatar answered Oct 06 '22 02:10

Bergi