The Ternary Operator: if/else in One Line

Grade 4, page 7 of 11. A one-minute read.

Sometimes you just want to pick between two values based on a condition. Writing a full if/else for that feels like a lot of typing:

JavaScript
const age = 20;
let message;

if (age >= 18) {
  message = "adult";
} else {
  message = "minor";
}

console.log(message);

It prints

adult

JavaScript has a shortcut for exactly this situation. It's called the ternary operator (because it has three parts), and it looks like this:

JavaScript
condition ? valueIfTrue : valueIfFalse

So the code above becomes:

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

It prints

adult

Read it like a question: "Is age at least 18? If yes, "adult". Otherwise, "minor"." The ternary is great inside template literals too:

JavaScript
const itemCount = 1;
console.log(`You have ${itemCount} ${itemCount === 1 ? "item" : "items"} in your cart.`);

const lives = 0;
console.log(lives > 0 ? "Keep playing!" : "GAME OVER 💀");

It prints

You have 1 item in your cart.
GAME OVER 💀
TipKeep ternaries simple

Ternaries are perfect for simple "this or that" choices. But you can chain them together, and things get ugly fast: a ? b : c ? d : e ? f : g. Yikes. If you find yourself doing that, go back to a normal if/else if. Readable code beats clever code every single time.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning