3

Do we have a ternary operator in Jscript (as opposed to JavaScript)? If so, what is the syntax?

2
  • 1
    Please note: Java, JScript and JavaScript are separate languages.
    – Incognito
    Commented Mar 10, 2011 at 14:01
  • @Incognito given that JScript and JavaScript are separate languages, why changing the title?
    – edc65
    Commented Jun 5, 2015 at 23:54

4 Answers 4

5

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.

2

yes it does.

test ? expression1 : expression2
1

Example:

var result = 5 > 10 ? '5 is greater than 10' : '5 is not greater than 10';
2
  • 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
    – svv
    Commented Mar 10, 2011 at 14:00
0

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.");

Not the answer you're looking for? Browse other questions tagged or ask your own question.