muudless muudless - 1 year ago 78
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download