why null == undefined?

K

k0t1k

Sorry if I am kicking the dead horse, but why null == undefined in
Rhino? This is what I got running Rhino shell.

$ java -jar js.jar
Rhino 1.6 release 1 2004 11 30
js> null == undefined
true
js> var a;
js> var b = null;
js> a == b
true
js> "" + a
undefined
js> "" + b
null
js>

Obviously Rhino knows the difference between two. I run into this
problem while trying to figure out way to distinguish situation when
object does not have a member with given name from situation when
object does have a member, but its value is null.

targetObject[ memberName ] != undefined

did not work

( "" + targetObject[ memberName ] ) != ( "undefined" )

does work, but looks ugly.
Any suggestions, insights, will be highly appreciated.
Andrei Tchijov
 
M

Michael Winter

Sorry if I am kicking the dead horse, but why null == undefined in
Rhino?

Because it is supposed to be. The == operator is a 'loose' comparison
operator that often causes type-conversion. In this instance, the null
and undefined primitive types are considered equal. You can either use
the strict equality operator === or a typeof test:

var n = null,
u;

typeof n == typeof undefined // false

to make the distinction. In the latter case, typeof null evaluates to
the string, 'object', whereas typeof undefined evaluates to 'undefined'.

Using the strict equality operator

a === b

is equivalent to

(typeof a == typeof b) && (a == b)

[snip]

Mike
 
K

k0t1k

Michael,
Thanks a lot for quick reply. It makes perfect sense. "!==" is
exactly what I was looking for.

Andrei
 
M

Martin Honnen

k0t1k said:
Obviously Rhino knows the difference between two. I run into this
problem while trying to figure out way to distinguish situation when
object does not have a member with given name from situation when
object does have a member, but its value is null.

If you know you have full ECMAScript edition 3 support such as in Rhino
then if all you want to know whether an object has a certain member is doing
"propertyName" in object
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
VetaMcRae
Top