3

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.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • 1
    just found one possible answer-- use `Object.keys(testObject)`. – temporary_user_name Apr 07 '17 at 10:32
  • I think you are looking for `undefined` and `null` – JustARandomProgrammer Apr 07 '17 at 10:32
  • No, I'm not. I don't know what would give you that impression. I'm not new to JavaScript. – temporary_user_name Apr 07 '17 at 10:33
  • Since you're not new to JavaScript you know https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined for sure. Which indeed leeds to the assumption you want to distinguish between `undefined` and `null`. If not, your question does not make much sense... – Oliver Hader Apr 07 '17 at 10:38
  • 1
    It's especially funny if you go to my profile and look at my highest voted answer. – temporary_user_name Apr 07 '17 at 10:43
  • @Aerovistae I don't see any point to start a fight here and also I'm surprised of you being so upset. At least for me your question was too vague and did not make much sense - what I wrote. I guess your question is answered in the duplicate then, isn't it? – Oliver Hader Apr 07 '17 at 11:00

3 Answers3

4

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
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
shivam Gupta
  • 441
  • 4
  • 7
  • Just a pointer. You should try to explain why changes you made would work. Just saying `Try this`, is not a good answer – Rajesh Apr 07 '17 at 10:54
3

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
}
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • `in` will also pass for properties on prototype and will fail for non-enumerable properties – Rajesh Apr 07 '17 at 10:49
2
testObject.hasOwnProperty('a')

Note that this will only work for objects like you show; inherited properties from prototype won't pass this test (which is the point of hasOwnProperty).

deceze
  • 510,633
  • 85
  • 743
  • 889