Using null in if statement

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

    #1

    Using null in if statement

    Hi.

    I remember using if statements with null in it. For example, at one
    point I used this:

    if (value == null) {
    value = "something" ;
    }

    document.write( value)

    However, this script causes an error in any browser. Why can't it
    correct the value like it should?
  • Robert

    #2
    Using null in if statement

    In article <c0espb$deg$1@n ews.netins.net> ,
    Brody <brody_jh02@hot mail.com> wrote:
    [color=blue]
    > if (value == null) {
    > value = "something" ;
    > }
    >
    > document.write( value)[/color]

    Javascript allows you to define a variable, but not initialize it

    A variable can be of state:
    - If you try to retrieve data from a variable that doesn't exist you get
    a runtime error. You can set a variable that hasn't appeared in a var
    statement. This gets set in external global.
    - A somewhat ambigous state where the variable has appeared in a var
    statement but you never set it to anything.
    - Set to null which means not data has been assigned. This is different
    than ""
    - Contains data. This include "".

    I don't fully understand the results of the third if

    <html>
    <head>
    <title>variab le contents</title>
    </head>
    <body>
    <p> blah, blah, blah, blah, blah...</p>
    <script type="text/javascript">

    var aVariable;
    aVariable = null;
    if (aVariable == null)
    {
    //This path
    document.write( "aVariable = " + aVariable);
    document.write( "<br><br>") ;
    }
    else
    {
    document.write( "aVariable is not null<br>");
    }

    var bVariable;
    bVariable = "";
    if (bVariable == null)
    {
    document.write( "bVariable is null");
    }
    else
    {
    //This path
    document.write( "bVariable *" + bVariable +
    "* length = " + bVariable.lengt h);
    document.write( "<br><br>") ;
    }


    // Third if
    var value;

    if (value == null)
    {
    //This path
    document.write( "value = " + value);
    document.write( "<br>");
    value = "value now contains data<br>";
    document.write( value);
    }
    else
    {
    document.write( "not null<br>");
    }

    //This will generate an error
    /*
    if (noDefinedValue == null)
    {
    noDefinedValue = "something" ;
    }
    */
    </script>
    <p>no blah</p>
    </body>
    </html>

    Comment

    Working...