tags:

views:

52

answers:

3

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.

+4  A: 

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
+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
A: 

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
they're "falsey"!
olliej
@ollej: yes, sure. I've modified the language to make this clearer.
ars
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
@Ken: great point, thank you. I fixed the example output.
ars
A: 

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"));
Peter Ajtai