Skip to main content

Ternary operator

The ?: operator, or the ternary operator, is a shorthand form of the if...else conditional. It lets you write the condition, the check, and both result options in a single line.


Syntax

javascript
condition ? expression_if_true : expression_if_false

How it works

  1. First, the condition is evaluated.
  2. If it is truthy (true), the first expression is returned.
  3. If it is falsy (false), the second expression is returned.

Example

javascript
const age = 20; const message = age >= 18 ? 'Access granted' : 'Access denied'; console.log(message); // "Access granted"

Here, age >= 18 is the condition. Since it is true, the first part is returned ('Access granted').


The same thing with if...else

javascript
let message; if (age >= 18) { message = 'Access granted'; } else { message = 'Access denied'; }

The ?: operator is simply a compact way of writing if...else.


Example with a function

javascript
function checkAccess(role) { return role === 'admin' ? 'Full access' : 'Limited access'; } console.log(checkAccess('admin')); // "Full access"

The ternary operator returns a value

Unlike if, the ternary operator is an expression, not just a statement. That means it can be used directly in an assignment, in function arguments, and so on:

javascript
console.log(5 > 3 ? 'Yes' : 'No'); // "Yes"

Nested ternary operators (be careful!)

Sometimes you'll come across nested ternary expressions:

javascript
const age = 25; const category = age < 13 ? 'child' : age < 20 ? 'teenager' : 'adult'; console.log(category); // "adult"

It works correctly, but hurts readability, so for complex conditions it's better to use a regular if...else.


Example with logic in expressions

javascript
const user = { name: 'Tim', premium: true }; const label = user.premium ? 'Premium' : 'Standard'; console.log(label); // "Premium"

Combination with && and ||

The ternary is often used together with other logical operators:

javascript
const access = user && user.isAdmin ? 'OK' : 'DENIED';

Summary

PartWhat it does
conditionChecked for true/false
? expression1Runs if the condition is true
: expression2Runs if the condition is false

Ternary operator examples

javascript
let score = 75; let result = score >= 60 ? 'Passed' : 'Failed'; console.log(result); // "Passed" let color = (score > 90) ? 'green' : (score > 70) ? 'orange' : 'red'; console.log(color); // "orange"

In short

NotationMeaning
a ? b : cIf a is true → return b, otherwise → c
ReturnsThe result of the selected expression
Can be used inAssignments, functions, templates, JSX, etc.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.