3.6 Ternary Operators
The ternary operator — also called the conditional operator — is a concise way to pick between two values based on a condition. Suppose we want to apply a simple business rule: if a customer has more than 100 points they are a "gold" customer, otherwise they are a "silver" customer. Let's express that in JavaScript.
First we declare a variable to track the points:
let points = 110;
let type = points > 100 ? 'gold' : 'silver';
console.log(type); // "gold"
How the ternary operator reads
The syntax follows three parts separated by ? and ::
- A condition that produces a boolean — here
points > 100. - A value used if the condition is
true— here'gold'. - A value used if the condition is
false— here'silver'.
If we change points to 90, the same expression evaluates to 'silver'. The ternary operator is perfect for short, inline decisions. For more elaborate branching, the regular if / else statement remains clearer. In the next video, we'll dive into logical operators.
Summary
This lesson introduces the ternary (conditional) operator in JavaScript, a compact syntax for assigning values based on conditions. Using a customer loyalty example, it demonstrates how to categorize clients as "gold" (points > 100) or "silver" otherwise. The syntax is `condition ? value_if_true : value_if_false`, providing a more concise alternative to if/else statements for simple assignments.
Key points
- The ternary operator is a conditional expression that evaluates a condition and returns one of two values
- Syntax structure: condition ? value_if_true : value_if_false
- Used for assigning different values to variables based on boolean conditions
- The condition produces a true or false result that determines which value is used
- More concise than if/else for simple conditional assignments
- Example: let type = points > 100 ? 'gold' : 'silver'
FAQ
What is the syntax of the ternary operator?
The syntax is condition ? value_if_true : value_if_false. If the condition evaluates to true, the first value is assigned; if false, the second value is assigned instead.
How is the ternary operator different from an if/else statement?
The ternary operator is a compact expression used specifically for conditional value assignment, while if/else is a control flow statement. The ternary operator is more efficient when you simply need to assign different values based on a condition.
What happens in the example when the points value is changed to 90?
When points equals 90, the condition 'points > 100' evaluates to false, so the variable 'type' is assigned the value 'silver' instead of 'gold'.