Need help understanding the JavaScript ternary operator

I’m trying to clean up some if/else statements in my JavaScript code by using the ternary operator, but I’m getting confused about the correct syntax and when it’s actually a good idea to use it. Some of my ternary expressions are getting hard to read, and I’m not sure if I’m nesting them wrong or misusing them. Can someone explain how to properly use the JavaScript ternary operator with clear examples, including best practices and common pitfalls?

Ternary is shorter if/else, nothing magic.

Basic syntax:
condition ? valueIfTrue : valueIfFalse

Example, normal if:

let msg;
if (age >= 18) {
msg = ‘adult’;
} else {
msg = ‘minor’;
}

Ternary version:

const msg = age >= 18 ? ‘adult’ : ‘minor’;

Key rules that keep it sane:

  1. Use it for expressions, not for big logic
    Good:
    const color = isError ? ‘red’ : ‘green’;

Bad:
isError
? doErrorStuff()
: doSuccessStuff();

If you are calling functions or doing multiple things, use if/else.

  1. Do not chain a lot
    You can do this:

const size = n > 10
? ‘big’
: n > 5
? ‘medium’
: ‘small’;

But it gets hard to read fast. Once you start thinking too long, use if/else instead.

  1. Do not mix assignment styles
    Avoid:

condition ? a = 1 : b = 2;

Use:

const value = condition ? 1 : 2;

Or:

if (condition) {
a = 1;
} else {
b = 2;
}

  1. Use parentheses when nesting in larger expressions

return isValid
? formatValue(x)
: defaultValue;

or:

const label = isValid
? formatValue(x)
: defaultLabel;

  1. Ternary returns a value
    If you do not use the value, skip ternary. For side effects, code reads better with if.

Bad:
isValid ? saveUser() : logError();

Better:

if (isValid) {
saveUser();
} else {
logError();
}

  1. Common patterns

Default fallback:

const name = userName ? userName : ‘Guest’;

With nullish coalescing you often use:

const name = userName ?? ‘Guest’;

Simple mapping:

const statusText = isOnline ? ‘Online’ : ‘Offline’;

  1. When to use ternary
    Use ternary when:
    • You assign a single value based on a simple condition
    • You return a single value from a function
    • Both branches are short and symmetric

Use if/else when:
• You do multiple statements per branch
• You need to debug inside the branches
• The condition or expressions are complex

If you post one of your ternary attempts that looks wrong, people can help fix the exact syntax and maybe suggest where if/else would be clearer.

The ternary is just an expression tool, but it’s really easy to abuse it and make the code worse instead of better.

Couple of angles that might help, without repeating what @caminantenocturno already covered:


1. Think: “What is the value here?”

If you can literally say this sentence:

“I want X to be either A or B, depending on condition C.”

then ternary fits.

Example thought:
“I want label to be either 'Adult' or 'Minor' depending on age.”

Code:

const label = age >= 18 ? 'Adult' : 'Minor';

If your sentence sounds like:

“If this, do 3 different things, otherwise log something, then maybe return…”

That’s an if, not a ternary.


2. Don’t let it pretend to be a statement

This one bites a lot of people:

isValid ? saveUser() : logError();

Technically fine, but logically weird: ternary returns a value that you just ignore. You’re treating an expression like a statement. Use it only when you need the value:

const handler = isValid ? saveUser : logError;
handler();

That pattern is where ternary actually shines.


3. Compare “before and after” to see if it’s really cleaner

Take an actual piece of your code and rewrite it both ways, then ask: which one would Future You understand faster?

Example:

// Version A
let price;
if (isVip) {
  price = basePrice * 0.8;
} else {
  price = basePrice;
}

// Version B
const price = isVip ? basePrice * 0.8 : basePrice;

B is clearly cleaner.

But:

// Ternary abuse
const price = isVip
  ? basePrice * 0.8 + getTax(basePrice * 0.8)
  : basePrice + getTax(basePrice);

At that point, if/else with some intermediate variables is usually easier to read and debug.


4. Chaining ternaries: use this gut-check

Chained ternaries can be ok, and I’m a bit more tolerant of them than @caminantenocturno, but only if:

  • All branches are the same kind of thing (e.g., all strings, or all simple numbers), and
  • The condition reads top to bottom like a priority list.

Example that’s still fairly readable:

const level =
  score >= 90 ? 'A' :
  score >= 80 ? 'B' :
  score >= 70 ? 'C' :
  score >= 60 ? 'D' :
  'F';

If you need to squint or add comments for each branch, turn it back into if/else or a mapping object.


5. Consider alternatives that are not ternary or if

Sometimes neither ternary nor if is best.

For multiple cases, an object map can be clearer:

const statusMap = {
  success: 'All good',
  error: 'Something broke',
  pending: 'Working on it'
};

const message = statusMap[state] ?? 'Unknown state';

Before reaching for a chained ternary, ask if a map like that would express the intent better.


6. Quick syntax mental template

When you feel “confused about syntax,” use this template and fill in the blanks:

const RESULT = CONDITION ? VALUE_IF_TRUE : VALUE_IF_FALSE;

If any of those placeholders need more than a short phrase, that’s usually a hint to not use ternary there, or to compute stuff first:

const discounted = basePrice * 0.8;
const regular = basePrice;

const price = isVip ? discounted : regular;

If you want, post one or two of the ternaries that feel wrong to you. Most of the time the issue isn’t syntax but that the code is trying to cram too much logic into a single line.