Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object.hasOwnProperty() vs Reflect.has()

Tags:

javascript

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'));
like image 306
Avid Programmer Avatar asked Nov 06 '19 10:11

Avid Programmer


2 Answers

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.

like image 145
CertainPerformance Avatar answered Nov 12 '22 23:11

CertainPerformance


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

like image 2
Ruslan Gataullin Avatar answered Nov 12 '22 22:11

Ruslan Gataullin