The Ternary Operator
Write compact one-line conditionals for simple either/or decisions — a concise alternative to if...else.
A shortcut for simple decisions
Sometimes you need a quick either/or decision to assign a value. With if/else, that takes at least 5 lines:
```
let message;
if (isLoggedIn) {
message = "Welcome back!";
} else {
message = "Please log in.";
}
```
The **ternary operator** lets you do the same thing in one line:
```
let message = isLoggedIn ? "Welcome back!" : "Please log in.";
```
It's called 'ternary' because it takes three parts: a condition, a result for true, and a result for false. It's not a replacement for all if/else statements — just the simple ones where you're picking between two values.
The ternary operator `? :` is the only JavaScript operator that takes three operands. It has been part of the language since the beginning and exists in nearly every C-family language (C, C++, Java, C#, PHP).