Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: if/else problem

  1. #1
    Regular Coder
    Join Date
    Jun 2008
    Posts
    102
    Thanks
    6
    Thanked 9 Times in 9 Posts

    if/else problem

    why is it that this does not work?
    Code:
    //var Variable = 2;
    
    if(Variable){
        alert('undefined');
    else{
        alert('defined');
    }
    I thought that if you test something in an if/else statement and it was undefined, then it meant false and went to the else part.

    I ran this in IE6 and FF and they both throw errors.

    but if(undefined) works fine. Whats the deal?

  • #2
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,511
    Thanks
    3
    Thanked 504 Times in 491 Posts
    the variable must be defined

    to check that it is defined


    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <script language="JavaScript" type="text/javascript">
    /*<![CDATA[*/
    //var Variable = 2;
    
    if(window['Variable']){
        alert('defined');
    }
    else{
        alert('undefined');
    }
    /*]]>*/
    </script>
    </body>
    
    </html>
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • #3
    Regular Coder
    Join Date
    Jun 2008
    Posts
    102
    Thanks
    6
    Thanked 9 Times in 9 Posts
    thanks bro!

    do you have to have the CDATA part for the window['name'] to work, and does this work with any JS supporting browser?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •