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
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.:andvalueIfFalse: what it gives when the condition is false.
See Conditional (ternary) operator (opens in a new tab) on MDN.
Prerequisites
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
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
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
node stock.js
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:
node stock.js
In stock
Now the condition is true, so the ternary gives the value after the question mark.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Leaving out the : valueIfFalse part | Node.js stops with SyntaxError: Unexpected token ';' | Always give both values |
| Putting several ternaries inside one another | The line works but gets hard to read | Use 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
- Conditional (ternary) operator (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments