Course contentsShow
← JavaScript
Lesson 228 of 2,7236. Booleans and ConditionalsFree lesson

Ternary as an Expression

Understand that ternaries return values, making them assignable and composable.

Ternary as an Expression

You'll learn: How the ternary operator returns a value, making it usable anywhere you need a result.


Unlike if statements, which perform actions, the ternary operator produces a value. This makes it an expression rather than a statement. You can assign its result to a variable, pass it as an argument, or embed it directly where a value is needed.

Why This Matters

Expressions can go places statements can't. You can store what a ternary evaluates to:

const status = age >= 18 ? "adult" : "minor";

Here, status receives either "adult" or "minor" depending on the condition. The ternary returns one of those strings, and that's what gets assigned.

Compare this to an if statement, which doesn't produce a value by itself:

// This doesn't work:
// const status = if (age >= 18) { "adult" } else { "minor" }

Expressions Are Composable

Because ternaries return values, you can use them inside other expressions:

const message = "You are " + (age >= 18 ? "allowed" : "not allowed");
console.log(score > 50 ? "Pass" : "Fail");
const discount = isPremium ? 0.20 : 0.10;
const finalPrice = basePrice * (1 - discount);

The ternary evaluates first, returns a value, and that value participates in the larger expression.

Think of It Like a Function

If you've used functions that return values, ternaries work similarly: they take a condition, evaluate it, and hand back one of two possible results. That result can go anywhere a value can go.


Key Takeaway: The ternary operator is an expression that returns a value, allowing you to assign, pass, or embed it wherever JavaScript expects a value.