Ternary operator
Ternary Operator
<script>
var a = 100;
var b;
(a == 100)? b = “true” : b = “false”;
document.write(b);
</script>
<script>
function getFee(isMember) {
return (isMember ? ‘$2.00’ : ‘$10.00’);
}
console.log(getFee(true));
console.log(getFee(false));
console.log(getFee(null));
console.log(getFee(null));
console.log(getFee(true));
</script>
<script>
var age = 26;
var beverage = (age >= 28) ? “Beer” : “Juice”;
document.write(beverage);
console.log(beverage); // “Beer”
</script>
<script>
var sheetincollage = 30;
var availablesheets = (sheetincollage <= 30)? “sheets are full” : “sheets are not full”;
document.write(availablesheets);
</script>
<script>
function example(…) {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
// Equivalent to:
function example(…) {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
</script>