The ternary operator (also called the conditional operator) is the only
JavaScript operator that takes three operands. It is frequently used as a shorthand for
an if...else statement.
The syntax for the ternary operator involves a question mark ? and a colon
:.
condition ? expressionIfTrue : expressionIfFalse;
How it works:
? is
executed.: is
executed.Imagine you want to check if a user is old enough to vote. Here is how you would do it in both ways:
let age = 20;
let voteable;
if (age >= 18) {
voteable = "Yes";
} else {
voteable = "No";
}
console.log(voteable); // "Yes"
let age = 20;
let voteable = (age >= 18) ? "Yes" : "No";
console.log(voteable); // "Yes"
While possible, you can "nest" ternary operators to handle more than two outcomes. However, this can become difficult to read very quickly.
let time = 10;
let greeting = (time < 12) ? "Good morning" : (time < 18) ? "Good afternoon" : "Good evening";
console.log(greeting); // "Good morning"
if...else if...else block.
The ternary operator is often used to provide a default value if data is missing:
let userName = null;
let display = userName ? userName : "Guest";
console.log(display); // "Guest"
? and : to make decisionsif...else for simple logic