#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 →
JavaScript Fundamentals

Ternary

The ternary operator is JavaScript's only operator that takes three operands: a condition, a value to use if it is truthy, and a value to use if it is falsy. Written as condition ? valueIfTrue : valueIfFalse, it is a compact way to choose between two values in a single expression, such as picking a label, a CSS class or a price.

Reading the syntax

Read it as a question: "Is the condition true? Then this, otherwise that." The condition comes first, followed by a question mark, the first result, a colon and the second result. Because the whole thing is an expression that produces a value, you can assign it, return it, or use it inside a template literal, which an if statement cannot do.

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

const items = 3;
const label = `${items} item${items === 1 ? "" : "s"}`;  // "3 items"

function shippingFee(total) {
  return total >= 500 ? 0 : 49;
}

// Chained ternary for a few clear cases
const score = 72;
const grade =
  score >= 90 ? "A" :
  score >= 75 ? "B" :
  score >= 60 ? "C" :
  "D";                                                // "C"

// Equivalent if...else
let statusIf;
if (age >= 18) {
  statusIf = "adult";
} else {
  statusIf = "minor";
}

Ternary versus if...else

Use a ternary whenUse if...else when
You are choosing between two valuesYou are running different blocks of statements
The result goes into a variable, return or templateEach branch does several things
Both branches are shortThere are many conditions or complex logic

The ternary is about values, not actions. Writing isValid ? save() : showError(); works, but it hides side effects inside an expression and reads poorly. An if statement states that intent more clearly.

Chaining and nesting

Because the operator is right-associative, you can chain several conditions, as in the grade example. Laid out one condition per line, a short chain is readable. Nesting a ternary inside the first branch of another, however, quickly turns into a puzzle. If you reach three or four levels, switch to if...else, a switch, or a lookup object.

The concatenation trap

The ternary has very low precedence, lower than +. That causes a well-known bug:

const msg = "Status: " + isOnline ? "online" : "offline";

JavaScript first computes "Status: " + isOnline, which is a non-empty string and therefore truthy, so msg is always just "online", without the prefix. Wrap the ternary in parentheses, "Status: " + (isOnline ? "online" : "offline"), or use a template literal, where the expression is already isolated inside ${ }.

Truthy and falsy conditions

The condition does not need to be a real boolean. Values like 0, an empty string, null, undefined and NaN count as false. That means count ? count : "none" shows "none" when count is 0, which may not be what you want. When zero or an empty string are valid values, test explicitly, or use the nullish operator: count ?? "none" falls back only for null and undefined.

Where you will see it often

Ternaries are everywhere in React components, because JSX accepts expressions but not if statements. Code such as {isLoggedIn ? <Logout /> : <Login />} chooses which element to render.

Takeaway: use condition ? a : b to pick between two values, keep both branches short, wrap it in parentheses when combining with +, and switch to if...else once the logic grows.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course