Ternary operators
suggest changeCan 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:
const animal = 'kitty';
const 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 look like with if/else.
const animal = 'kitty';
let 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.
let a = 0;
let str = 'not a';
let 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’.
The conditional operator always requires the : branch. A syntax error is thrown if it is missing. When the result is unused, the other branch can be a harmless expression such as 0.
const 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
// The operator is right-associative. This example groups 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.
Each branch must be an expression. break and return are statements, so the following snippets are syntax errors.
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:
const animal = 'kitty';
return (animal === 'kitty') ? 'meow' : 'woof';