muudless muudless - 1 month ago 4
Javascript Question

How do you use the ? : (conditional) operator in JavaScript?

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

(conditional, "ternary") operator and how to use it?


This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

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;

1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.