The Ternary Operator

Write compact one-line conditionals for simple either/or decisions — a concise alternative to if...else.

Step 1 of 5

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.

Think of it this way: The ternary operator is like a quick text message reply: 'Is it raining? Umbrella : Sunglasses' — one line, two options, done. No need to write a whole paragraph when a quick answer will do.
Web Standard

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).