Summary
The conditional operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if
statement.
Operator | |
Implemented in: | JavaScript 1.0 |
ECMA Version: | ECMA-262 |
Syntax
condition ? expr1 : expr2
Parameters
-
condition
-
An expression that evaluates to
true
orfalse
.
-
expr1
,expr2
- Expressions with values of any type.
Description
If condition
is true
, the operator returns the value of expr1
; otherwise, it returns the value of expr2
. For example, to display a different message based on the value of the isMember
variable, you could use this statement:
document.write ("The fee is " + (isMember ? "$2.00" : "$10.00"))
You can also assign variables depending on a ternary result:
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";
Multiple ternary evaluations are also possible (note: the conditional operator is right associative):
var hadRelations = false, isSure = false, presidentQuote = hadRelations ? "Had relations" : isSure ? "Did not have relations" : "I admit"; console.log( presidentQuote ); // Prints "I admit" in the console
You can also use ternary evaluations in free space in order to do different operations:
var bStop = false, nAge = 16; nAge > 18 ? location.assign("continue.html") : bStop = true;
You can also do more than one single operation per case, separating them with a comma:
var bStop = false, nAge = 23; nAge > 18 ? ( alert("Ok, you can go."), location.assign("continue.html") ) : ( bStop = true, alert("Sorry, your are too much young!") );
You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned.
var nAge = 16; var sURL = nAge > 18 ? ( alert("Ok, you can go."), // alert returns "undefined", but it will be ignored because isn't the last comma-separated value of the parenthesis "continue.html" // the value to be assigned if nAge > 18 ) : ( alert("You are too much young!"), alert("Sorry :-("), // etc. etc. "stop.html" // the value to be assigned if !(nAge > 18) ); location.assign(sURL); // "stop.html"