Codectionary / Developer documentation / JavaScript

Ternary Operator

The ternary (conditional) operator is a compact one-line alternative to an if...else statement. It takes the form condition ? valueIfTrue : valueIfFalse, and evaluates to whichever value matches the condition. It is an expression, meaning it produces a value that can be assigned or used directly, unlike an if statement.

Syntax

condition ? valueIfTrue : valueIfFalse

Examples

Basic Ternary

Assigning a value based on a condition in a single line.

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

Ternary in JSX-style Rendering

A common pattern for conditional rendering in template-like code.

const isLoggedIn = true;
const message = isLoggedIn
  ? `Welcome back!`
  : `Please log in.`;

console.log(message);

// Nested ternaries are possible but hurt readability - use sparingly
const grade = 85;
const letter = grade >= 90 ? "A" : grade >= 80 ? "B" : grade >= 70 ? "C" : "F";

Best practices

  • Use the ternary operator for simple, single-condition value assignments - reach for if...else when logic gets more complex
  • Avoid deeply nested ternaries, as they quickly become hard to read - a switch or if/else chain is often clearer
  • Wrap ternaries in parentheses when used inside template literals or JSX for clarity
  • Remember it is an expression (produces a value), unlike if/else which is a statement

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation