muudless muudless - 6 months ago 33
Javascript Question

How to use the ?: (ternary) operator in JavaScript

Can someone please explain to me in simple words what is the

(ternary) operator and how to use it?


This is a one-line shorthand for an if-then statement. It is called a ternary operator or a conditional operator.

Here is an example of code that could be shortened with the conditional operator:

if(userIsYoungerThan21) {
else {

This can be shortened with the ?: like so:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

In Javascript conditional operator can evaluate to an expression, not just a statement:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";
serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

They can even be chained:

userIsYoungerThan4 ? serveMilk() : userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

Be careful, though, or you will end up with convoluted code like this:

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;