Tutorial

JavaScript Ternary Operators

JavaScript
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.

Creative Commons License