1condition ? doThisIfTrue : doThisIfFalse
2
31 > 2 ? console.log(true) : console.log(false)
4// returns false
1//ternary operator syntax and usage:
2condition ? doThisIfTrue : doThisIfFalse
3
4//Simple example:
5let num1 = 1;
6let num2 = 2;
7num1 < num2 ? console.log("True") : console.log("False");
8// => "True"
9
10//Reverse it with greater than ( > ):
11num1 > num2 ? console.log("True") : console.log("False");
12// => "False"
1var age = 26;
2var beverage = (age >= 21) ? "Beer" : "Juice";
3console.log(beverage); // "Beer"
4
1function example(…) {
2 return condition1 ? value1
3 : condition2 ? value2
4 : condition3 ? value3
5 : value4;
6}
7
8// Equivalent to:
9
10function example(…) {
11 if (condition1) { return value1; }
12 else if (condition2) { return value2; }
13 else if (condition3) { return value3; }
14 else { return value4; }
15}
16