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'));