Say I have the object testObject = {a: undefined}. If I then console.log(testObject.a), I get undefined. But the same happens if I console.log(testObject.b), which doesn't exist. Is there any way in JavaScript to distinguish between a and b here? I ask mostly out of curiosity, I have no use case.
hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property.
In given case -
testObject = {a: undefined};
testObject.hasOwnProperty('a') // true
testObject.hasOwnProperty('b') // false
You can actually distinguish with extra condition before checking using in operator
if(a in testObject) {
// it's there .. now check whether it is undefined or not
}
hasOwnProperty() method returns a boolean indicating whether the object has the specified property as own (not inherited) property.
In given case -
testObject = {a: undefined};
testObject.hasOwnProperty('a') // true
testObject.hasOwnProperty('b') // false
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