16

in javascript:

d={one: false, two: true}
d.one
d.two
d.three

I want to be able to differentiate between d.one and d.three. By default they both evaluate to false, but in my case they should not be treated the same.

priestc
  • 33,060
  • 24
  • 83
  • 117

3 Answers3

24

You can do

"one" in d // or "two", etc

or

d.hasOwnProperty("one")

You probably want hasOwnProperty as the in operator will also return true if the property is on the an object in the prototype chain. eg.

"toString" in d // -> true

d.hasOwnProperty("toString") // -> false
olliej
  • 35,755
  • 9
  • 58
  • 55
  • 1
    +1. `hasOwnProperty` for when you're treating an `Object` as a general-purpose string->value lookup; `in` for when you're checking for instance capabilities. – bobince Oct 16 '10 at 02:16
0

The values aren't strictly false:

js> d={one: false, two: true}
[object Object]
js> d.one == false
true
js> d.three == false
false
js> d.three === false
false    
js> d.three === undefined
true
js> 'three' in d
false
js> 'one' in d
true

Also, see comments by olliej and Ken below.

ars
  • 120,335
  • 23
  • 147
  • 134
  • @ollej: yes, sure. I've modified the language to make this clearer. – ars Oct 16 '10 at 01:31
  • 1
    Your response is on the right track, but these examples are kind of misleading, particularly since you're still using the type-coercion-inducing `==` operator in all cases. To elaborate, `d.three === null` would be `false`, but `d.three === undefined` would be `true` (but would be more safely tested as `typeof d.three === "undefined"`, since `undefined` is mysteriously *not* a reserved word). For that matter, just plain `!d.three` would also be `true`. This is because `null == false == undefined == 0 == ""` - all of these things are falsey. – Ken Franqueiro Oct 16 '10 at 03:24
-1

Well, d.one is false and d.three is undefined.

var d={one: false, two: true};
alert("one: " + d.one + "\nthree: " + d.three);
  // Output:
  // one: false
  // three: undefined

Try it out with this jsFiddle

Javascript does have some funky true false evaluation at times, but this isn't one of those situations:

alert(d.three == false);                                          // alerts false

To check for undefined you can use typeof

if (typeof something  == "undefined") 

Or you can check if three is a property of d

if (d.hasOwnProperty("three"));
Community
  • 1
  • 1
Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140