Curriculum Series

What is the ternary operator?

What is the ternary operator?

What is the ternary operator?

JavaScript

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

JAVASCRIPT
1// if/else
2let message;
3if (age >= 18) {
4 message = 'Adult';
5} else {
6 message = 'Minor';
7}
8
9// Ternary — one line
10const message = age >= 18 ? 'Adult' : 'Minor';

In React/JSX

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

JAVASCRIPT
1function Status({ isOnline }) {
2 return (
3 <span className={isOnline ? 'green' : 'gray'}>
4 {isOnline ? 'Online' : 'Offline'}
5 </span>
6 );
7}

When NOT to use it

Avoid nesting ternaries — they become hard to read:

JAVASCRIPT
1// Bad — hard to read
2const label =
3 score > 90
4 ? 'A'
5 : score > 80
6 ? 'B'
7 : score > 70
8 ? 'C'
9 : 'F';
10
11// Better — use if/else or a function
12function getGrade(score) {
13 if (score > 90) return 'A';
14 if (score > 80) return 'B';
15 if (score > 70) return 'C';
16 return 'F';
17}

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 — 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.

Finished reading?

Mark this topic as solved to track your progress.