DEV Community

Cover image for JavaScript Ternary Operator
Meg
Meg

Posted on

JavaScript Ternary Operator

One of my favorite parts of the JavaScript language is the JavaScript Ternary Operator.

At heart, it’s a succinct, clean way of writing an if/else statement.

You start by asking a question,
"Is this item a circle?"

If the item is a circle, it takes path one
If the item is not a circle, it takes path two

You would write it in JavaScript like this:

circle ? true : false

A ternary operator can also be stacked or ‘nested’.

In this example the item we’ll use is a triangle.

You would use the same first condition:

circle ? true : _____

And replace the false condition with a second ternary:

triangle ? true : false

So a nested ternary would be:

circle ? true : triangle ? true : false

You can stack as many conditions as you like and adjust the formatting to visually appear like a switch statement:

circle ?
true : triangle ?
true : square ?
true : rectangle ?

You are also able to return with a ternary operator by listing "return" before your condition:

return circle ? true : false

Unpacking this statement, it should read:
Is the item a circle?
If the item is a circle, return true
If the item is not a circle, return false

By using "return" with a ternary you must always return from either condition. It's not able to be used in instances where you only want to return on true, but not false, and vice versa.

All in all, I hope this helped understand the JavaScript Ternary Operator a bit better and why I find it so visually clean and fun to use.

Top comments (0)