Generally, the ternary operator means:
condition ? (value returned if condition is true) : (value returned if condition is false)
In your example, the condition is sex && sex === 'Man'
, which means that the value contained in the variable sex
is truthy and strictly equal to the string "Man"
.
Here's the breakdown:
var salutation;
if(sex && sex === 'Man') {
salutation = 'Mr';
} else {
salutation = 'Ms';
}
Furthermore, in this particular example, since you are using strict equality (i.e. ===
) comparison, there isn't any point to the truthfulness check for sex
, it is unnecessary. Your condition can just be:
var salutation = sex === "Man" ? "Mr." : "Ms.";
Explanation: When using &&
, both operands are coerced to booleans first so their "truthfulness" can be AND-ed. For example, let's say sex = 'Man'
, then your condition would essentially be:
if('Man' && 'Man' === 'Man')
Which coerced to booleans is:
if(true && true)
Which is clearly redundant. Read more about JavaScript type coercion.
This truthy check is a good safety check in other situations that happen when using a non-strict comparison operator such as ==
, <
, >
... instead of ===
.
In simple terms, using ==
first coerces both items to the same type before comparing which can lead to bugs. Using ===
immediately returns false
if the types differ, hence it is safer.
Here's a another useful resource for JavaScript comparisons.