Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Conditional (ternary) operator

Picks one of two values by a condition — a short if...else.

Available since: ES1

Syntax

condition ? valueIfTrue : valueIfFalse

Examples

Picking a value:

const age = 20;
 
console.log(age >= 18 ? 'adult' : 'minor');

Output:

adult

Inside a template literal:

const count = 1;
 
console.log(`${count} ${count === 1 ? 'item' : 'items'}`);

Output:

1 item

Notes

Good for choosing a value in one expression. Do not nest ternaries — for several options if...else or switch read better.

See also

In the tutorial

  • Conditions — Branching in JavaScript — if, else, else if, truthy and falsy values and the ternary operator.

Thanks for reading!

Donate to the site — we work hard for you.