This tutorial is out of date and no longer maintained.
Ternary operators allow us to really quickly write shorter if
statements.
Here’s a quick example:
// chris is level 100 cool
// everyone else is level 999
const howCoolAmI = name === 'chris' ? 100 : 999;
Let’s take a deeper look at how we can rewrite a simple if
statement with and without a ternary operator:
If statement without a ternary operator:
let skillLevel;
if (name === 'chris') {
skillLevel = 5;
} else {
skillLevel = 10;
}
We can rewrite the above with a ternary operator like so:
let skillLevel = name === 'chris' ? 5 : 10;
?
).?
) will be what is returned if true
.:
) will be what is returned if false
.Here we have a CodePen similar to the earlier examples. Feel free to play around with this and see how we can use JavaScript ternary operators.
https://codepen.io/chrisoncode/pen/orOEjd?editors=1010
If you need extra room and your ternary is getting too long for a single line (an 80 character limit can be typical), you can split ternary statements into multiple lines.
const howCoolAmI = name === 'chris'
? 100
: 999;
Ternary operators are just an operator that accepts 3 parts. What we’ve used throughout this article is just a conditional operator with 3 parts and that’s why it’s often referred to as the ternary operator. This is fine since JavaScript has only one operator that accepts 3 operands.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.