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 4 of 4
  1. #1
    Regular Coder
    Join Date
    Feb 2003
    Posts
    638
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Ternary... null vs. [ "" ]

    test ? expression1 : expression2
    Just wondering which is more correct, when omitting the 2nd expression:

    test ? expression1 : "";
    or
    test ? expression1 : null;

    I'm thinking: null
    hmm... ?

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    Depends on the situation. What type should the return value of the ternary expression be? If it's string, use '', if it's number, use Number.NaN or 0 or -1 depending on situation, if it's boolean you probably don't need to use ternary operator at all, if it's a function or an object it should be either null or undefined (which for backward compatibility should be void(0)).
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    Regular Coder
    Join Date
    Feb 2003
    Posts
    638
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Lightbulb

    Found a reference...
    Null Data Type

    The null data type has only one value in JScript: null. The null keyword cannot be used as the name of a function or variable.

    A variable that contains null contains "no value" or "no object." In other words, it holds no valid number, string, Boolean, array, or object. You can erase the contents of a variable (without deleting the variable) by assigning it the null value.

    Notice that in JScript, null is not the same as 0 (as it is in C and C++). Also note that the typeof operator in JScript will report null values as being of type Object, not of type null. This potentially confusing behavior is for backwards compatibility.

    Platform SDK: JScript Data Types
    So it seems null is best.
    hmm... ?

  • #4
    Regular Coder
    Join Date
    Feb 2003
    Posts
    638
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by liorean
    Depends on the situation...
    Oops, looks like I was posting while you replied; this was about boolean...

    When using dynamic properties in IE, like style="expression(...);", the if Statement doesn't work, so the ternary seems necessary in its place.

    Thanks for explaining.
    hmm... ?


  •  

    Posting Permissions

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