Can be used to shorten if/else operations. This comes in handy for returning a value quickly (i.e. in order to assign it to another variable).
For example:
var animal = 'kitty';
var result = (animal === 'kitty') ? 'cute' : 'still nice';
In this case, result
gets the 'cute' value, because the value of animal is 'kitty'. If animal had another value, result would get the 'still nice' value.
Compare this to what the code would like with if/else
conditions.
var animal = 'kitty';
var result = '';
if (animal === 'kitty') {
result = 'cute';
} else {
result = 'still nice';
}
The if
or else
conditions may have several operations. In this case the operator returns the result of the last expression.
var a = 0;
var str = 'not a';
var b = '';
b = a === 0 ? (a = 1, str += ' test') : (a = 2);
Because a
was equal to 0, it becomes 1
, and str
becomes 'not a test'. The operation which involved str
was the last, so b
receives the result of the operation, which is the value contained in str
, i.e. 'not a test'.
Ternary operators always expect else conditions, otherwise you'll get a syntax error. As a workaround you could return a zero something similar in the else branch - this doesn't matter if you aren't using the return value but just shortening (or attempting to shorten) the operation.
var a = 1;
a === 1 ? alert('Hey, it is 1!') : 0;
As you see, if (a === 1) alert('Hey, it is 1!');
would do the same thing. It would be just a char longer, since it doesn't need an obligatory else
condition. If an else
condition was involved, the ternary method would be much cleaner.
a === 1 ? alert('Hey, it is 1!') : alert('Weird, what could it be?');
if (a === 1) alert('Hey, it is 1!') else alert('Weird, what could it be?');
Ternaries can be nested to encapsulate additional logic. For example
foo ? bar ? 1 : 2 : 3
// To be clear, this is evaluated left to right
// and can be more explicitly expressed as:
foo ? (bar ? 1 : 2) : 3
This is the same as the following if/else
if (foo) {
if (bar) {
1
} else {
2
}
} else {
3
}
Stylistically this should only be used with short variable names, as multi-line ternaries can drastically decrease readability.
The only statements which cannot be used in ternaries are control statements. For example, you cannot use return or break with ternaries. The following expression will be invalid.
var animal = 'kitty';
for (var i = 0; i < 5; ++i) {
(animal === 'kitty') ? break:console.log(i);
}
For return statements, the following would also be invalid:
var animal = 'kitty';
(animal === 'kitty') ? return 'meow' : return 'woof';
To do the above properly, you would return the ternary as follows:
var animal = 'kitty';
return (animal === 'kitty') ? 'meow' : 'woof';