test ? expression1 : expression2
Just wondering which is more correct, when omitting the 2nd expression:
test ? expression1 : "";
test ? expression1 : null;
I'm thinking: null
05-03-2004, 08:24 PM
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)).
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.
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. :)