This is a one-line shorthand for an if-else statement. It's called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
var codeName;
if (userIsYoungerThan18) {
codeName = "Minor";
} else {
codeName = "Adult";
}
if (memberCheck) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}
This can be shortened with the ?: like so:
var codeName = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(memberCheck ? "Grape Juice" : "Wine");
Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
memberCheck ? serveGrapeJuice() : serveWine();
They can even be chained:
serveDrink(userIsYoungerThan4 ? 'Milk' : memberCheck ? 'Grape Juice' : 'Wine');
Be careful, though, or you will end up with convoluted code like this:
var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
function getFee(isMember) {
return (isMember ? '$2.00' : '$10.00');
}
console.log(getFee(true));
// expected output: "$2.00"
console.log(getFee(false));
// expected output: "$10.00"
console.log(getFee(null));
// expected output: "$10.00"
Ref : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
Logical AND Operator
const a = true, b = false;
const c = 4;
// logical AND
console.log(a && a); // true
console.log(a && b); // false
console.log((c > 2) && (c < 2)); // false
Using AND
a1 = true && true // t && t returns true
a2 = true && false // t && f returns false
a3 = false && true // f && t returns false
a4 = false && (3 == 4) // f && f returns false
a5 = 'Cat' && 'Dog' // t && t returns "Dog"
a6 = false && 'Cat' // f && t returns false
a7 = 'Cat' && false // t && f returns false
a8 = '' && false // f && f returns ""
a9 = false && '' // f && f returns false