Do we have a ternary operator in Jscript (as opposed to JavaScript)? If so, what is the syntax?
4 Answers
It's
expression ? expression : expression
just like C. It's a little looser, actually, because JavaScript is not strongly-typed. Thus the two possible "forks" of the operator can result in different types of values.
Thus:
alert(document.all ? "Hello from IE!" : "Hello from a non-IE browser!");
Most of the time, the differences between Microsoft's ECMAScript and those found in other browsers (or other server-side environments) aren't really that great, and for ordinary non-DOM code it's pretty rare to have to deal with such things.
Example:
var result = 5 > 10 ? '5 is greater than 10' : '5 is not greater than 10';
-
For clarity sake, and to insure proper precedence of operators, and to make this ultimately readable I would restate the rhs as ((5 > 10) ? '5 is greater than 10' : '5 is not greater than 10') Commented Mar 10, 2011 at 13:59
-
Thanks ZeSimon.. My Bad.. I just made some syntactical errors in my code and keep wondering why ternary doesn't working– svvCommented Mar 10, 2011 at 14:00
You can always use google to find language syntax, too.
The first result I got was, http://msdn.microsoft.com/en-us/library/be21c7hw%28v=vs.85%29.aspx. It has examples like
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");