Ternary operator ⇒ a shortcut to if() and else() statements.
help to assign a variable based on a condition
- condition
?codeIfTure:codeIfFalse;
Ternary code:
let age = 21;
let mesage = age >= 18 ? "you're an adult" : "you're a minor" ;Normal code:
let age = 21;
let message;
if(age >= 18){
message = "you're an adult";
}
else{
message = "you're a minor";
}These two code have same function, ternary operator a simple way of the if statement
Another example:
let purchaseAmount = 99;
let discount = purchaseAmount >= 100 ? 10 : 0;
console.log(`your total is ${purchaseAmount - purchaseAmount * (discount / 100 )}`);