Skip to main content
0 reactions

How to Use the Ternary Operator in JavaScript

A card titled The Ternary Operator, labelled JavaScript Basics, showing copiesLeft compared with 0, the two labels In stock and Sold out, and the result Sold out.
The Ternary Operator: Pick one of two values in a single line of JavaScript.

The ternary operator, also called the conditional operator, picks one of two values in a single expression. It’s a short form of an if…else that gives back a value.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
condition ? valueIfTrue : valueIfFalse
  • condition: anything that’s true or false, such as a comparison.
  • ?: comes after the condition.
  • valueIfTrue: what the expression gives when the condition is true.
  • : and valueIfFalse: what it gives when the condition is false.

See Conditional (ternary) operator (opens in a new tab) on MDN.

Prerequisites

The Example

A label for a book in a shop: it should say “Sold out” when no copies are left. copiesLeft starts at 0. The file is stock.js.

Step 1: Write the Code

stock.jsJavaScript
const copiesLeft = 0;
const label = copiesLeft > 0 ? "In stock" : "Sold out";

console.log(label);

The ternary checks copiesLeft > 0 and stores one of the two labels in label.

Step 2: Run It

TerminalBash
node stock.js
OutputPlain text
Sold out

copiesLeft > 0 is false, so the ternary gives the value after the colon.

Step 3: Change the Value

Change the first line to const copiesLeft = 4; and run it again:

TerminalBash
node stock.js
OutputPlain text
In stock

Now the condition is true, so the ternary gives the value after the question mark.

Common Mistakes

MistakeWhat happensDo this instead
Leaving out the : valueIfFalse partNode.js stops with SyntaxError: Unexpected token ';'Always give both values
Putting several ternaries inside one anotherThe line works but gets hard to readUse if…else for more than two choices

FAQ

When should I use if…else instead?

When a branch does more than give back a value, such as running several lines, or when there are more than two choices.

Conclusion

condition ? valueIfTrue : valueIfFalse picks one of two values in one line. Use it when both branches just give back a value.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments