why null == undefined?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • k0t1k

    why null == undefined?

    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

  • Michael Winter

    #2
    Re: why null == undefined?

    On 22/06/2005 20:56, k0t1k wrote:
    [color=blue]
    > Sorry if I am kicking the dead horse, but why null == undefined in
    > Rhino?[/color]

    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

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.

    Comment

    • k0t1k

      #3
      Re: why null == undefined?

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

      Andrei

      Comment

      • Martin Honnen

        #4
        Re: why null == undefined?



        k0t1k wrote:
        [color=blue]
        > 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.[/color]

        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
        "propertyNa me" in object


        --

        Martin Honnen

        Comment

        Working...