two different conditions in ternary operator javascript code example
Example 1: javascript ternary operator
condition ? doThisIfTrue : doThisIfFalse
let num1 = 1;
let num2 = 2;
num1 < num2 ? console.log("True") : console.log("False");
num1 > num2 ? console.log("True") : console.log("False");
Example 2: ternary operator for multiple conditions
String year = "senior";
if (credits < 30) {
year = "freshman";
} else if (credits <= 59) {
year = "sophomore";
} else if (credits <= 89) {
year = "junior";
}
Contrast this with the ternary operator:
String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";