Ternary Operator (? :)
Ternary Operator (? :)
Use (? :) (ternary) as a shorthand for if...else.
Syntax
condition ? valueIfTrue : valueIfFalse;
Using if...else
let age = 20;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
Using Ternary
let age = 20; let result = age >= 18 ? "Adult" : "Minor"; console.log(result);
Output:
Adult
Example
condition ? expression1 : expression2