We're live-coding on Twitch! Join us!
JavaScript Ternary Operators

JavaScript Ternary Operators


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:

Without a ternary operator

// if statement without a ternary operator
let skillLevel;

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

With a 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 **?**.
  • The first part after the ? will be what is returned if true.
  • The second part after the : will be what is returned if false.

Interactive Example of a Ternary Operator

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.

Multi-Line Ternary Operator

If you need extra room and your ternary is getting too long for a single line (I like keeping an 80 character limit), you can split ternary statements to multiple lines.

const howCoolAmI = name === 'chris' 
                                ? 100 
                                : 999; 

A Note About Naming

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.

Like this article? Follow @chris__sev on Twitter