Report this

What is the reason for this report?

JavaScript Ternary Operators

Draft updated on Invalid Date
Chris on Code

By Chris on Code

JavaScript Ternary Operators
This tutorial is out of date and no longer maintained.

Introduction

Ternary operators allow us to really quickly write shorter if statements.

Writing a Ternary Operator

Here’s a quick example:

// chris is level 100 cool
// everyone else is level 999
const howCoolAmI = name === 'chris' ? 100 : 999;

Diagram of the ternary operator. 100 is returned if true. 999 is returned if false.

Let’s take a deeper look at how we can rewrite a simple if statement with and without a ternary operator:

If / Else

If statement without a ternary operator:

let skillLevel;

if (name === 'chris') {
  skillLevel = 5;
} else {
  skillLevel = 10;
}

Rewritten as Ternary Operator

We can rewrite the above with a ternary operator like so:

let skillLevel = name === 'chris' ? 5 : 10;
  • To use a ternary we will put the if statement on the left of the question mark (?).
  • The first part after the question mark (?) will be what is returned if true.
  • The second part after the colon (:) 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

Using Multi-Line Ternary Operators

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; 

Conclusion

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.

Learn more about our products

About the author

Chris on Code
Chris on Code
Author
Category:

Still looking for an answer?

Was this helpful?


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!

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.