Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to distinguish between an unset property and a property set to undefined? [duplicate]

Tags:

javascript

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.

like image 593
temporary_user_name Avatar asked Oct 22 '25 04:10

temporary_user_name


3 Answers

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
like image 131
shivam Gupta Avatar answered Oct 24 '25 05:10

shivam Gupta


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
}
like image 34
Suresh Atta Avatar answered Oct 24 '25 06:10

Suresh Atta


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
like image 25
shivam Gupta Avatar answered Oct 24 '25 06:10

shivam Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!