What is the ternary operator?

The short answer

The ternary operator (condition ? valueIfTrue : valueIfFalse) is a shorthand for a simple if/else that returns a value. It takes three operands: a condition, a value to return if true, and a value to return if false. It is commonly used in JSX for conditional rendering.

How it works

// if/else
let message;
if (age >= 18) {
message = 'Adult';
} else {
message = 'Minor';
}
// Ternary: one expression
const label = age >= 18 ? 'Adult' : 'Minor';

In React/JSX

The ternary is the most common way to do conditional rendering in JSX:

function Status({ isOnline }) {
return (
<span className={isOnline ? 'green' : 'gray'}>
{isOnline ? 'Online' : 'Offline'}
</span>
);
}

When NOT to use it

Avoid nesting ternaries. They become hard to read:

// Bad: hard to read
const label =
score > 90
? 'A'
: score > 80
? 'B'
: score > 70
? 'C'
: 'F';
// Better: use if/else or a function
function getGrade(score) {
if (score > 90) return 'A';
if (score > 80) return 'B';
if (score > 70) return 'C';
return 'F';
}

Use the ternary for simple, one-level conditions. For anything more complex, use if/else or extract a function.

Interview Tip

Show the basic syntax, a JSX example, and mention that nested ternaries are bad practice. This is a quick question, so keep it brief.

Why interviewers ask this

This tests basic JavaScript syntax knowledge. It often comes up in the context of React, where ternaries are used constantly in JSX.