#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Operators

Ternary Operator in JavaScript: Simplifying Conditional Logic

What is the Ternary Operator?

The ternary operator ?: is a shorthand for a simple if...else statement, evaluating a condition and returning one of two values.

Syntax

condition ? valueIfTrue : valueIfFalse;

Example

let age = 20;
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message); // "Adult"

When to Use It

Ternary operators are best for short, simple conditions. For multiple conditions or complex logic, if...else or switch statements are more readable.

How JavaScript Evaluates a Ternary

The ternary operator works in three small steps:

  1. JavaScript evaluates the condition before the ?.
  2. If the result is truthy, it evaluates and returns the expression after ?.
  3. If the result is falsy, it evaluates and returns the expression after :.

Only one of the two branches runs. That matters when a branch calls a function, because the other function is never called. The condition also does not need to be a real boolean. Values such as 0, an empty string, null, undefined and NaN count as false, and almost everything else counts as true.

const items = [];
const label = items.length ? `${items.length} items` : "Your cart is empty";
console.log(label); // "Your cart is empty", because 0 is falsy

Because the ternary is an expression that produces a value, it can go places an if statement cannot: inside a template literal, as a function argument, in an object property or as the return value of an arrow function.

Practical Patterns You Will Use Often

// Inside a template literal
const qty = 1;
console.log(`You bought ${qty} ${qty === 1 ? "ticket" : "tickets"}`);

// As the body of an arrow function
const shippingFee = (total) => (total >= 500 ? 0 : 40);

// Choosing a CSS class name
button.className = isActive ? "btn btn-active" : "btn";

// Several conditions, formatted one per line
const grade =
  score >= 90 ? "A" :
  score >= 75 ? "B" :
  score >= 60 ? "C" :
  "Fail";

The last pattern chains ternaries. It reads well when each line is a simple check, as above. Once a branch needs more than one value or any extra logic, switch to if...else.

In React code you will see ternaries constantly, because JSX only accepts expressions: {isLoggedIn ? <Dashboard /> : <Login />}.

Ternary or a default-value operator?

GoalBest tool
Pick between two different resultscond ? a : b
Use a fallback only for null or undefinedvalue ?? "default"
Use a fallback for any falsy valuevalue || "default"

For example, count ?? 10 keeps a real count of 0, while count || 10 would replace it with 10.

Mistakes That Make Ternaries Buggy

  • Operator precedence with strings. "Status: " + isOnline ? "On" : "Off" always gives "On", because the string is joined first and a non-empty string is truthy. Write "Status: " + (isOnline ? "On" : "Off").
  • Using it only for side effects. isValid ? save() : showError(); works, but an if statement states the intention more clearly when nothing is returned.
  • Deep nesting on one line. Nested ternaries without line breaks become puzzles. Format them vertically or replace them with a lookup object or switch.
  • Trying to put statements inside. Branches must be expressions, so return, let or for cannot appear inside a ternary.

A simple rule: if you can read the line aloud as "if this, then that, otherwise the other" without pausing, the ternary is a good fit.

Ready to master real-world JavaScript development?

Learn JavaScript hands-on with mentor-led, live sessions.

Explore Course