Back to List

Ternary Operator β€” Conditions in One Line

This article summarizes the principles, usage, and reasons why the JavaScript ternary operator should not be overused.

Beginner
|
7min
|
Verified (2026-07)
ternary operatorternaryconditional renderingJSXconditional expression
Progress0/55 (0%)

Ternary Operator β€” Conditions in One Line

After Completing This Topic

You will understand the structure of the ternary operator, be able to replace if/else statements with a single line, and be able to judge when a ternary operator is appropriate and when it becomes difficult to read.


Transforming 4 Lines of if into 1 Line

For simple branching scenarios like "Allow access if an adult, otherwise deny":

javascript
let message;
if (age >= 18) {
  message = "Access allowed";
} else {
  message = "Access denied for minors";
}

Using the ternary operator reduces it to a single line:

javascript
const message = age >= 18 ? "Access allowed" : "Access denied for minors";

Structure: condition ? value if true : value if false

The key point is that the ternary operator returns a value. While if is a statement that doesn't return a value, the ternary operator is an expression that can be directly assigned to a variable.


Basic Patterns

javascript
// Pattern 1: Variable assignment
const status = score >= 60 ? "Pass" : "Fail";

// Pattern 2: Function argument
console.log(isLoggedIn ? "Welcome" : "Please log in");

// Pattern 3: Inside a template literal
const greeting = `${hour < 12 ? "AM" : "PM"} ${hour % 12} o'clock`;

Commonality: The ternary operator is natural when you need to "choose one of two values," and that choice can be done in a single line.


Ternary in React/JSX

In React, the ternary operator is almost essential because you cannot use if statements inside JSX:

jsx
function UserGreeting({ isLoggedIn, name }) {
  return (
    <div>
      {isLoggedIn ? (
        <h1>Hello, {name}!</h1>
      ) : (
        <button>Log In</button>
      )}
    </div>
  );
}

Inside JSX's curly braces {}, only expressions can be used. if/else is a statement and cannot be used, making the ternary operator the only inline conditional branching method.


Nested Ternary β€” Temptation and Pitfall

When you need to branch more than twice, you might be tempted to nest ternary operators:

javascript
// ❌ Difficult to read
const label = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";

This code works, but it will take time to interpret if you read it six months later. Even with indentation, nested ternary operators are hard to read.

Alternative 1 β€” if/else:

javascript
// βœ… Clear
let label;
if (score >= 90) label = "A";
else if (score >= 80) label = "B";
else if (score >= 70) label = "C";
else label = "F";

Alternative 2 β€” Object mapping or function extraction:

javascript
function getGrade(score) {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  return "F";
}
const label = getGrade(score);

Ternary vs. && (Logical AND)

In React, for cases where "render if the condition is true, otherwise render nothing":

jsx
// Ternary β€” explicitly return null
{isAdmin ? <AdminPanel /> : null}

// `&&` operator β€” more concise
{isAdmin && <AdminPanel />}

&& is cleaner than the ternary operator when you don't need to render anything if the condition is false. However, there is a caveat:

jsx
// ⚠️ Dangerous: If `count` is 0, "0" will be rendered on the screen
{count && <ItemList />}

// βœ… Safe: Explicitly convert to a boolean
{count > 0 && <ItemList />}

0 is a falsy value, but React renders the number 0 on the screen. When the left side of && is a number, you should use a comparison operator to convert it to a boolean.


Difference from Nullish Coalescing (??)

javascript
// Ternary: Choose one of two values based on the condition
const display = value !== null ? value : "Default value";

// `??`: Replace only if null or undefined
const display = value ?? "Default value";

?? filters only null and undefined. It passes through falsy values such as 0, "", and false. The ternary operator can use any condition, making it more versatile, while ?? is specialized for the narrow use case of providing a default value when a value is missing.


Decision Criteria

ScenarioRecommendation
Choose one of two values to assignβœ… Ternary
JSX inline conditional renderingβœ… Ternary or &&
More than 3-way branching❌ if/else or function extraction
Side effects (API calls, etc.) included❌ if/else
Only replacing null/undefined❌ ?? operator

Use the ternary operator when it meets all three conditions: "Two choices, one line, returns a value." If even one of these is not met, use if/else.


Key takeaway: The ternary operator is condition ? A : B β€” an expression that chooses one of two values. If you nest it, it becomes hard to read, so revert to if/else when the branching becomes more complex.

πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...