I experienced using object.hasOwnProperty('property')
to validate Javascript object and recently noticed that Reflect.has()
also used to validate the object properties.
However, both are almost the same functionality but I would like to understand the best practice to use Reflect.has()
and which one will cause better performance.
I noticed that if it is not an object then hasOwnProperty
is not throwing any error but Reflect.has()
throws an error.
var object1 = {
property1: 42
};
//expected output: true
console.log(object1.hasOwnProperty('property1'));
console.log(Reflect.has(object1, 'property1'));
// expected output: true
console.log(Reflect.has(object1, 'property2'));
// expected output: false
console.log(Reflect.has(object1, 'toString'));
//For Negative case scenario
var object2 ="";
// expected output: false
console.log(object2.hasOwnProperty('property1'))
// error
console.log(Reflect.has(object2, 'property1'));
One major difference is that Reflect.has
will check whether any of the object's internal prototypes have the key, whereas hasOwnProperty
only checks whether the object itself has the key:
const proto = { foo: 'foo' };
const obj = Object.create(proto);
console.log(Reflect.has(obj, 'foo'));
console.log(obj.hasOwnProperty('foo'));
If you want to check whether the object itself has the property, and isn't an inherited property, you should definitely use hasOwnProperty
.
Another important difference is that Reflect.has
requires ES6 support, whereas hasOwnProperty
has existed since ES3, so if you use Reflect.has
and require support for older browsers, make sure to include a polyfill.
Reflect api is a part of ECMAScript 2015 whether hasOwnProperty is available in current standard. Their behavior may differ too. So if they function identically it only depends on whether you want to support older browsers or not.
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Reflect
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
You can polyfill it with seral libraries that can be found on github/npmjs like: https://www.npmjs.com/package/reflect-metadata
https://www.npmjs.com/package/harmony-reflect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With