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
1// if/else2let message;3if (age >= 18) {4 message = 'Adult';5} else {6 message = 'Minor';7}89// Ternary — one line10const message = age >= 18 ? 'Adult' : 'Minor';
In React/JSX
The ternary is the most common way to do conditional rendering in JSX:
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:
1// Bad — hard to read2const label =3 score > 904 ? 'A'5 : score > 806 ? 'B'7 : score > 708 ? 'C'9 : 'F';1011// Better — use if/else or a function12function 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.
Related React Ecosystem interview topics
Continue with nearby questions from the same topic cluster.